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.

 Akzeptierte Antwort

Geoff Hayes
Geoff Hayes am 2 Jul. 2014

0 Stimmen

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 Kommentare

Shi-hyung Lee
Shi-hyung Lee am 2 Jul. 2014
Thanks. It works. But I'm wondering if I have to compare, let's say A(i) with B(i-1), E(i) with B(i-2), F(i) with B(i-3) and so on. how can I do this?
I think your first approach was just as elegant - to me, there does not seem to be any need to create a D vector. Just use the comparison as
if A(i)<B(i)
Then, as you add more conditions, say for A(i) with B(i-1) you can build them into your if and (maybe) else if statements.
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 am 2 Jul. 2014
Solved the problem. I just have to do A(1:100)>B(2:101) and such things... What a fool I am..

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Communications Toolbox finden Sie in Hilfe-Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by