How to preform actions on rows based on conditions
1 view (last 30 days)
Show older comments
Hi,
I'll try to make it simple by ex.
A = [1 1 2 3 1; 2 1 2 3 1; 3 1 2 3 1; 4 3 2 1 2; 5 3 3 1 2; 6 4 3 2 3;]
B = [1 3 3 3 1]
Label = 2
Last column will is basically the data's label. I would like all the rows in A with the desired label multiplied by B.
Desired result:
C = [1 1 2 3 1; 2 1 2 3 1; 3 1 2 3 1; 4 9 6 3 2; 5 9 9 3 2; 6 4 3 2 3;]
Even more complected but not a must since I can work around it. Assume last value of B would also indicate a label, B = [1 3 3 3 2]. Can I have the same action done(would have to avoid multiplying last value)?
lines were missing, apologies.
Any way doing it or I must iterate over A?
0 Comments
Answers (1)
the cyclist
on 9 Nov 2015
Edited: the cyclist
on 9 Nov 2015
Here's one way:
% Inputs
A = [1 1 2 3 1; 2 1 2 3 1; 3 1 2 3 1; 4 3 2 1 2; 5 3 3 1 2; 6 4 3 2 3;]
B = [1 3 3 3 1]
Label = 2;
% Identify the rows whose last element is the label
rowsToMultiply = A(:,end)==Label;
% Multiply only those rows by B. (Use "bsxfun" to expand B to appropriate size.)
A(rowsToMultiply,:) = bsxfun(@times,A(rowsToMultiply,:),B)
0 Comments
See Also
Categories
Find more on Matrix Indexing 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!