How to preform actions on rows based on conditions

1 view (last 30 days)
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?

Answers (1)

the cyclist
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)

Community Treasure Hunt

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

Start Hunting!