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 CenterFile Exchange에서 Communications Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by