Error when defining variable with if statement and add to table
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Hello! I want to define the variable 'm' with an if statement with 3 conditions and add this defined variable to a table for further calculations. But using this code gives me an error.
a=[1,2];
b=[2,6,10];
l=[1:20:100];
[a,b,l]=ndgrid(a,b,l);
a=a(:);
b=b(:);
l=l(:);
disp=([a,b,l])
if (b==2)
m = 100
elseif (b==6)
m = 1000
elseif (b==10)
m = 10000
end
disp([a,b,l,m])
Error using horzcat
Dimensions of arrays being concatenated are not consistent.
Error in test (line 20)
disp([a,b,l,m])
Does someone know what I´m doing wrong?
0 Commenti
Risposte (4)
Fangjun Jiang
il 8 Mag 2019
the size of a, b and l is 30x1 but the size of m is 1x1
1 Commento
Fangjun Jiang
il 8 Mag 2019
Modificato: Fangjun Jiang
il 8 Mag 2019
I guess you want
m=b;
m(b==2)=100
m(b==6)=1000
m(b==10)=10000
then you can do
disp([a,b,l,m])
KALYAN ACHARJYA
il 8 Mag 2019
Modificato: KALYAN ACHARJYA
il 8 Mag 2019
First Issue:
a=[1,2];
b=[2,6,10];
l=[1:20:100];
[a,b,l]=ndgrid(a,b,l);
a=a(:);
b=b(:);
l=l(:);
disp=([a,b,l])
if (b==2)
m = 100
elseif (b==6)
m = 1000
elseif (b==10)
m = 10000
end
disp([a,b,l,m])
If you run the code, you will get the error, as m is undefined, as neither b==2,b==6 or b==10, b value from the code is vector 30x1, not scalar single value. These if condition are not satisfied in any three cases, therefore m value is not assigned, so its reflects the error m is undefined.
Second Case:
If you manage to run the if condition anyhow, then m value assigned as one scalar value.
Due to different sizes of a,b,l,m, it cannot concanated. Where a,b,l are 30x1, whereas m will a scalar value.
Hope it helps!
0 Commenti
Patrick Maier
il 8 Mag 2019
1 Commento
Fangjun Jiang
il 8 Mag 2019
Modificato: Fangjun Jiang
il 8 Mag 2019
You could use the code in my answer, or
m=b;
for k=1:numel(m)
if b(k)==2
m(k) = 100;
elseif b(k)==6
m(k) = 1000;
elseif b(k)==10
m(k) = 10000;
end
end
Vedere anche
Categorie
Scopri di più su Matrices and Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!