Info

Cette question est clôturée. Rouvrir pour modifier ou répondre.

How can I make a code with if/ else function?

1 vue (au cours des 30 derniers jours)
Jiyeon Kim
Jiyeon Kim le 26 Jan 2019
Clôturé : MATLAB Answer Bot le 20 Août 2021
for i=1:sz(1) %sz(1) is 21
k = find(xi == XX(i) & yi == YY(i));
disp(zi(k))
w(i,1)=zi(k)
end
When I run above code, it shows error with this statement
"Unable to perform assignment because the size of the left side is 1-by-1 and the size of the right side
is 0-by-1.
Error in sur3 (line 151)
w(i,1)=zi(k)"
so I made another code to run the code anyway, and set the data that cannot be found in my data(xi, yi) as o(zero)
for i=1:siz1(1)
if k == find(xi == XX(i) & yi == YY(i));
disp(zi(k))
w(i,1)=zi(k)
else k==[]
w(i,1)=0
end
w(i,1)=zi(k)
end
for i=1:siz1(1)
if (XX(i)==xi) & (YY(i) == yi )
k = find(xi == XX(i) & yi == YY(i));
disp(zi(k))
w(i,1)=zi(k)
else (XX(i) ~= xi) | (YY(i) ~= yi);
w(i,1)=0
end
end
but it didnt work as well..
I want to find data which satisfy xi == XX(i) & yi == YY(i))
If there is no data for that, I just wanna set the w(i,1) as zero n jump to the next step to find data..
How can i fix this problem..?

Réponses (1)

John D'Errico
John D'Errico le 26 Jan 2019
Modifié(e) : John D'Errico le 26 Jan 2019
Part of your problem is in this test:
else k==[]
Why is that an issue? Because you can't do it. For example, suppose I create an explicitly empty array, then do that same test.
E = [];
E == []
ans =
0×0 empty logical array
Hmm. It did not recognize E as empty, at least not by that test. Instead, you need to use isempty.
isempty(E)
ans =
logical
1
Or, I suppose you could have tested the number of elements in E.
numel(E) == 0
ans =
logical
1
Another issue is in the else itself. An if statement will be in this form:
help if
if Conditionally execute statements.
The general form of the if statement is
if expression
statements
ELSEIF expression
statements
ELSE
statements
END
So if you wanted to do a test, then you need to use elseif.
elseif isempty(k)
  2 commentaires
Jiyeon Kim
Jiyeon Kim le 26 Jan 2019
for i=1:siz1(1)
if k == find(xi == XX(i) & yi == YY(i));
disp(zi(k))
w(i,1)=zi(k)
elseif isempty(k)
w(i,1)=0
end
end
I tried this code using elseif that u recommend ,, but it doesnt work becase I got w matrix consist of only zeros..
Steven Lord
Steven Lord le 27 Jan 2019
Define k to be the result of that find call then use if and isempty to test if it is empty. If it is, set the corresponding element of w to 0. If it is not, set the corresponding element of w to the associated element in zi.

Cette question est clôturée.

Community Treasure Hunt

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

Start Hunting!

Translated by