Help to find errors of if loop?
古いコメントを表示
Example Complex: for,if... loop;
clear;clc;
A=[400; 900; 200; 300; 100];
k=[4;1]; % index matrix
c=[11];
e=zeros(0);
for j=0:(length(k)-1);
b(j+1,:) = A(k(j+1,:), :); % call vector from index
if b(j+1,:)>200
c=union(c,b(j+1,:));
elseif (b(j+1,:)+100)>400
e=union(e,b(j+1,:));
end
end
I try to run the simpe above code to understand: if elseif loop.
Explanation of code (for ...end):
-j=0-->k(1,:)=4-->b(4,:)=A(4,:)=300 [get value from matrix A at index 4]
-j=1-->k(2,:)=1-->b(1,:)=A(1,:)=400 [get value from matrix A at index 1]
Finally we will have result matrix b=[300;400]----> GOOD
But for the (if ....elseif ...end), i hope that the result matrix e=[400], but when I run the code matrix e=[] ?????????? Can you help me where the error?
My understanding of all loops:
-j=0-->k(1,:)=4-->b(4,:)=A(4,:)=300
if b(4,:)=300>200 ---> c=[11 300]
elseif b(4,:)=300+100=400>400 : NO--->e=[]
-j=1-->k(2,:)=1-->b(1,:)=A(1,:)=400
if b(1,:)=400>200 ---> c=[11 300 400]
elseif b(1,:)=400+100=500>400: YES --->e=[400]
Finally: e=[400] : as my understanding? (How can i fix the code to get the result as my understanding)
4 件のコメント
Jan
2017 年 8 月 30 日
Note that there are no "if loops". Only for and while are loops, while if branches according to a condition.
Inventing an own syntax like
-j=0-->k(1,:)=4-->b(4,:)=A(4,:)=300 [get value from matrix A at index 4]
is not useful for a discussion as long, as you do not define what the symbols mean. "-j=0-->k(1.:)=4" ? It would not be smart, if I guess, what this means. Why is the valid Matlab syntax not sufficient to explain the problem? You can assume that the readers are familiar with it.
Adam
2017 年 8 月 30 日
For starters j = 0 is not a valid index into an array and
e=zeros(0);
just creates an empty matrix.
@Adam, the j=0 is not a problem as all indexing is done with j+1. Of course, rather than going from 0 to numel(k)-1 and then adding one to all the values for indexing, it would be a lot simpler to just go from 1 to numel(k) and not add anything:
for j = 1:numel(k)
b(j) = A(k(j, :), :);
is a lot simpler.
採用された回答
その他の回答 (0 件)
カテゴリ
ヘルプ センター および File Exchange で プログラミング についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!