Find Min of Matrix without using MIN or explicit loops (FOR or WHILE)
Show older comments
I am reviewing for a test and my teacher loves to ask us questions that require the removal of explicit loops (FOR and WHILE) and use implicit (Array Operations) instead. For example instead of
for n=1:100
b=sin(n);
end
b
instead use
n=1:100;
b=sin(n);
b
so the function we are to convert is as follows A is an arbitrary predifined Matrix
clear,clc
for m=1:length(A(1,:));
S(m)=A(1,m);
for k=2:length(A(:,1));
if(S(m)>A(k,m))
S(m)=A(k,m);
end
end
end
S
Where S is a vector with the minimum value of each column. I know this could be solved with Min(A), but that is not what is being ask. How would I use vectorization to make the same above operation to work?
Answers (2)
John D'Errico
on 1 May 2011
0 votes
Well, perhaps you might look at the tools matlab provides. What directory does the function min reside in? (which will help you here.)
Look at the other tools in that same directory. Would any of them be capable of helping you?
2 Comments
Stephen Smitherman
on 1 May 2011
John D'Errico
on 1 May 2011
I was not telling you to read the source code for min, something I know that you cannot do. However, had you looked in that directory, you would have found various functions. Reading about them would quickly have taught you about a few of the tools available in matlab. One of those functions is sort, a tool which does allow you to solve the problem, as others have by now shown. Your teacher is trying to teach you to think outside of your normal patterns. Follow that lead.
Matt Fig
on 1 May 2011
Here is a way to do it without MATLAB loops. Though I think the idea John has in mind would be better!
mn = sort(A);
mn = mn(1,:);
3 Comments
Stephen Smitherman
on 1 May 2011
Stephen Smitherman
on 1 May 2011
Matt Fig
on 1 May 2011
Let me see. No loops and no function calls? You could hand write a bunch of consecutive IF statements, thereby limiting the size allowed for the input. Other than that I don't see how it could be done without either loops or some function call.
Categories
Find more on Programming in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!