How to add values to matrix in a loop given an extra condition.

2 ビュー (過去 30 日間)
Stefan Juhanson
Stefan Juhanson 2021 年 4 月 1 日
コメント済み: Stefan Juhanson 2021 年 4 月 1 日
I have a 101 x 2 matrix and i need to make n x 1 matrix where n = A(i,1)*A(i,2) and n has to be negative.
I.E : A = [1 -2
3 3
4 -5 ]
to A2 = [-2
-20]
heres my code at the moment:
A(:,1) = []
A(1:101,:) = []
A
i = 1;
H = [];
%length(A(:,1))
for i = 1: length(A(:,1))
if A(i,1)*A(i,2) < 0
H2=H(A(i,1)*A(i,2));
else
i=i+1;
end
end
H2
  1 件のコメント
Jan
Jan 2021 年 4 月 1 日
What is the purpose of these lines:
A(:,1) = []
A(1:101,:) = []
This deletes elements.
The FOR loop cares for the loop counter i already. Then te initial i=0 and i=i+1 are useless. Simply omit them.

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

採用された回答

Jan
Jan 2021 年 4 月 1 日
編集済み: Jan 2021 年 4 月 1 日
A = [1 -2; ...
3 3; ...
4 -5 ];
A2 = zeros(size(A, 1), 1); % Pre-allocate maximum number of elements
iA2 = 0; % Index inside A2
for iA = 1:size(A, 1) % Cleaner and faster than: length(A(:,1))
num = A(iA, 1) * A(iA, 2);
if num < 0
iA2 = iA2 + 1;
A2(iA2) = num;
end
end
A2 = A2(1:iA2); % Crop unused elements
The efficient matlab'ish way is:
A2 = A(:, 1) .* A(:, 2);
A2 = A2(A2 < 0);
or:
index = (A(:, 1) < 0) ~= (A(:, 2) < 0);
A2 = A(index, 1) .* A(index, 2)
  1 件のコメント
Stefan Juhanson
Stefan Juhanson 2021 年 4 月 1 日
Thanks, this works perfectly. The lines
A(:,1) = []
A(1:101,:) = []
were just to take wanted values from a bigger N x 2 matrix.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by