Error when defining variable with if statement and add to table

1 Ansicht (letzte 30 Tage)
Patrick Maier
Patrick Maier am 8 Mai 2019
Beantwortet: Patrick Maier am 8 Mai 2019
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?

Antworten (4)

Fangjun Jiang
Fangjun Jiang am 8 Mai 2019
the size of a, b and l is 30x1 but the size of m is 1x1
  1 Kommentar
Fangjun Jiang
Fangjun Jiang am 8 Mai 2019
Bearbeitet: Fangjun Jiang am 8 Mai 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])

Melden Sie sich an, um zu kommentieren.


KALYAN ACHARJYA
KALYAN ACHARJYA am 8 Mai 2019
Bearbeitet: KALYAN ACHARJYA am 8 Mai 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!

Patrick Maier
Patrick Maier am 8 Mai 2019
Ok got it. How can I change the if statement that m will also be a 30x1 vector with this conditions?
Like:
b m
2 100
6 1000
10 10000
..
  1 Kommentar
Fangjun Jiang
Fangjun Jiang am 8 Mai 2019
Bearbeitet: Fangjun Jiang am 8 Mai 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

Melden Sie sich an, um zu kommentieren.


Patrick Maier
Patrick Maier am 8 Mai 2019
Thank you so much!!

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Produkte


Version

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by