Error when defining variable with if statement and add to table

1 回表示 (過去 30 日間)
Patrick Maier
Patrick Maier 2019 年 5 月 8 日
回答済み: Patrick Maier 2019 年 5 月 8 日
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 日
the size of a, b and l is 30x1 but the size of m is 1x1
  1 件のコメント
Fangjun Jiang
Fangjun Jiang 2019 年 5 月 8 日
編集済み: Fangjun Jiang 2019 年 5 月 8 日
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 日
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 件のコメント
Fangjun Jiang
Fangjun Jiang 2019 年 5 月 8 日
編集済み: Fangjun Jiang 2019 年 5 月 8 日
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

サインインしてコメントする。


Patrick Maier
Patrick Maier 2019 年 5 月 8 日
Thank you so much!!

カテゴリ

Help Center および File ExchangeMatrices and Arrays についてさらに検索

タグ

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by