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

3 vues (au cours des 30 derniers jours)
Stefan Juhanson
Stefan Juhanson le 1 Avr 2021
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 commentaire
Jan
Jan le 1 Avr 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.

Connectez-vous pour commenter.

Réponse acceptée

Jan
Jan le 1 Avr 2021
Modifié(e) : Jan le 1 Avr 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 commentaire
Stefan Juhanson
Stefan Juhanson le 1 Avr 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.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by