if statement of type cell problem..

1 回表示 (過去 30 日間)
Shi-hyung Lee
Shi-hyung Lee 2014 年 7 月 2 日
コメント済み: Shi-hyung Lee 2014 年 7 月 2 日
It seems an easy problem but I just can't figure it out.
let A,B,C be vectors.
for i=1:100
if A(i)<B(i)
C(i)=0;
else
C(i)=1;
end
end
this code, of course, works well. but if I define, say D={A(i)<B(i)} and
for i=1:100
if D{1}==1
C(i)=0;
else
C(i)=1;
end
end
This code does not work. Looks like some kind of data type problem, but I just don't know how to fix it. Thanks in advance.

採用された回答

Geoff Hayes
Geoff Hayes 2014 年 7 月 2 日
Check out the condition in the second block of code
if D{1}==1
At each iteration, the code is comparing the first element of the cell array D with 1 when it should be considering each element of D. But I suspect that won't work either because of the way that D was initialized.
What is the code for that initialization? Was it simply
D = {A<B}
which is different from (but similar to) your example of D={A(i)<B(i)}. In the case of D = {A<B}, D is just a single element cell array with the first element being a logical vector of dimension mx1 (where m is the length of the vectors A and B). So accessing
D{1}
returns a mx1 logical array which can't be compared to the single digit one.
What you want to do instead is initialize D as follows
D = A<B;
which will be a mx1 array/vector of logical elements where a 1 in the ith position indicates that A(i)<B(i) and a zero indicates the opposite.
Your second block of code then becomes
D = A<B;
for k=1:100
if D(k)==1
C(k)=0;
else
C(k)=1;
end
end
Try the above and see what happens!
  4 件のコメント
Shi-hyung Lee
Shi-hyung Lee 2014 年 7 月 2 日
What I'm doing is like this.
Z={A<B C<D E<F};
for k=1:3
for i=1:100
if Z{k}(i)==1
X(i)=0;
else
X(i)=1;
end
end
name=['Result', num2str(k)];
xlswrite(name,X);
end
I guess there are not much differences in time and effort between doing manually and doing like this. But I just want to do it this way. That's all.
Shi-hyung Lee
Shi-hyung Lee 2014 年 7 月 2 日
Solved the problem. I just have to do A(1:100)>B(2:101) and such things... What a fool I am..

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCommunications Toolbox についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by