MATLAB Answers

0

Error when defining variable with if statement and add to table

Asked by Patrick Maier on 8 May 2019
Latest activity Answered by Patrick Maier on 8 May 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?

  0 Comments

Sign in to comment.

Products


Release

R2018b

4 Answers

Answer by Fangjun Jiang on 8 May 2019

the size of a, b and l is 30x1 but the size of m is 1x1

  1 Comment

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])

Sign in to comment.


Answer by KALYAN ACHARJYA on 8 May 2019
Edited by KALYAN ACHARJYA on 8 May 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 Comments

Sign in to comment.


Answer by Patrick Maier on 8 May 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 Comment

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

Sign in to comment.


Answer by Patrick Maier on 8 May 2019

Thank you so much!!

  0 Comments

Sign in to comment.