condition
显示 更早的评论
I am a new in Matlab I try to do condition with (if and elseif and else) for a simple arry but the condion equations that I put do not verified array a, what is the problem?
a=1:1:10
for m=1
for n=1:10
if a(m,n)<4
a=a*2
elseif a(m,n)>4
a=a*3
else
a=a*4
end
end
end
2 个评论
Paulo Silva
2011-7-11
please format your code, put it inside {}
Paulo Silva
2011-7-11
please explain what's the purpose of the code you want to do
回答(1 个)
bym
2011-7-12
your last condition is dead code, your conditions are either less than 4 or greater than 4, so the last 'else' statement is not used. Also, you do not need the for m= 1 loop. Here is an example:
a = 1:10
for k = 1:10
if a(k)<4
x(k)=a(k)*2;
elseif a(k)<8
x(k)=a(k)*3;
else
x(k) = a(k)*4;
end
end
[a;x]
5 个评论
Walter Roberson
2011-7-12
Unless the question was edited, I believe you have incorrectly determined the final condition to be "dead code". Consider when a(k) is 4 exactly: that is not less than 4, and it is not greater than 4, so the else would be reached and for that one case of a(k)==4 only, the code should multiply by 4.
Your code, though, would multiply the case of a(k)==4 by 3, and would multiply the cases of a(k)==8, a(k)==9, and a(k)==10 by 4 whereas the original code would multiply those cases by 3.
Walter Roberson
2011-7-12
Would multiply, that is, if the original poster had done the multiplications on a(k) instead of on _all_ of a.
Paulo Silva
2011-7-12
The OP doesn't seem very interested about his question, no explanation so far, I'm starting to ignore such questions and move on to other questions where the OP explained what he/she wants.
Jan
2011-7-12
@Paulo: Are the "Op has left the building" threads getting more in the last weeks? Or am I getting tired?
Paulo Silva
2011-7-12
Jan, just a few more than usual, must be vacations related, what's getting up on my nerves is the ones that post without enough details and expect us to decode what they want.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!