Define variable array with if statement using exiting arrays

I have two arrays creates, each 100x1 and I'm having trouble correctly using an ''if'' statement to create a third array comprised of elements in the first two arrays. This is what I have so far:
X1 = linspace(-5, 15)';
X2 = linspace(12, 0)';
y = X1|X2
if X1<X2
y = X1(:, 1);
else
y = X2(:, 1);
end
table = table(X1, X2, y)
The table I'm using to quickly check if I used my statements correctly. The 'y' array generates, however it's an exact match to 'X2' when it should contain values of both 'X1' and 'X2'. Could someone offer insite as to what I'm over looking or doing incorrectly?

回答 (1 件)

Sulaymon Eshkabilov
Sulaymon Eshkabilov 2020 年 9 月 4 日
編集済み: Sulaymon Eshkabilov 2020 年 9 月 4 日

0 投票

Hi,
a small loop would solve your exercise:
X1 = linspace(-5, 15)';
X2 = linspace(12, 0)';
for ii=1:numel(X1)
if X1(ii)<X2(ii)
y(ii,1) = X1(ii, 1);
else
y(ii,1) = X2(ii, 1);
end
end
table(X1, X2, y)
%% Much better solution and most efficient solution is LOGICAL INDEXING:
X1 = linspace(-5, 15)';
X2 = linspace(12, 0)';
in1 = (X1<X2);
Y(in1, 1)=X1(in1,1);
in2 = X2<X1;
Y(in2, 1) = X2(in2, 1);
table(X1, X2, Y)

カテゴリ

ヘルプ センター および File ExchangeTables についてさらに検索

質問済み:

2020 年 9 月 4 日

編集済み:

2020 年 9 月 4 日

Community Treasure Hunt

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

Start Hunting!

Translated by