while inside a loop.
2 次查看(过去 30 天)
显示 更早的评论
load cities.mat;
temp_ratings = sort(ratings,'descend');
for j=1:9
i=0;
temp_vec=zeros(1,9);
while temp_vec==zeros(1,9)
i=i+1
if temp_ratings(i+1)~=temp_ratings(i+2)
temp_vec=temp_ratings(i+2);
end
end;
end;
This is a code that i'm trying to write for homework. I need to find the 2nd Highest number in each column. I made easier codes, even without loops for this one, but i'm trying to make it a lil bit more sophisticated. The thing is that in some of the columns sometimes there're more than 1 elements that are presenting the highest number, so I need to take that in account.
This is the only direction that I'm trying to do, so i'm not looking too much for a new command or something more than I'm using here. Anyway - The problem with my code that it does what I want but only for the first column! I mean that the while command is working and after it gets the 'if' and stops the loop (of 'for' command).
What am i missing here? Thanks, Eran.
0 个评论
采纳的回答
dpb
2017-4-12
What you're missing here is the definition of 'True' in Matlab for vectors/arrays in if and while and other logical tests. From the doc's for while there's the following--
"while...repeats the execution of a group of statements in a loop while the expression is true. An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
The problem is your while condition is true iff there's never anything but 0 in temp_vec; as soon as you insert anything nonzero there, then temp_vec==zeros(1,9) will be false as every element in the resulting logical vector has to be true for the expression to be true.
Since you're trying as homework, I'll leave the hint at that for now...
7 个评论
dpb
2017-4-13
Then how about Accept ing the answer to at least indicate the thread has reached a satisfactory resolution?
I did figure that would be the case when it became clear... :) The uncertainty about logical if and arrays in Matlab always takes some time to come to grips with; it makes sense given how Matlab works and is quite powerful when understand the uses for logical arrays, but isn't intuitive at first.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!