Error when defining variable with if statement and add to table

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?

답변 (4개)

Fangjun Jiang
Fangjun Jiang 2019년 5월 8일

0 개 추천

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

댓글 수: 1

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
KALYAN ACHARJYA 2019년 5월 8일
편집: KALYAN ACHARJYA 2019년 5월 8일
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 2019년 5월 8일

0 개 추천

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

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

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2018b

태그

질문:

2019년 5월 8일

답변:

2019년 5월 8일

Community Treasure Hunt

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

Start Hunting!

Translated by