How to add values to matrix in a loop given an extra condition.
3 views (last 30 days)
Show older comments
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 Comment
Jan
on 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.
Accepted Answer
Jan
on 1 Apr 2021
Edited: Jan
on 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)
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!