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

5 Ansichten (letzte 30 Tage)
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 Kommentar
Jan
Jan am 1 Apr. 2021
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.

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Jan
Jan am 1 Apr. 2021
Bearbeitet: Jan am 1 Apr. 2021
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 Kommentar
Stefan Juhanson
Stefan Juhanson am 1 Apr. 2021
Thanks, this works perfectly. The lines
A(:,1) = []
A(1:101,:) = []
were just to take wanted values from a bigger N x 2 matrix.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by