Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorizing a for loop in MATLAB

In MATLAB, given a matrix A, I want to create a matrix B containing elements of matrix A as a percentage of the first column elements. The following code does it:

A = randi(5,6);

B = zeros(size(A,1), size(A,2));
for kk = 1:size(A,2)
    B(:,kk) = (A(:,kk).*100)./ A(:,1)-100;
end

However, how could I achieve the same result in a single line through vectorization? Would arrayfun be useful in this matter?

like image 612
AJMA Avatar asked May 07 '26 22:05

AJMA


1 Answers

Use bsxfun in this case:

B = bsxfun(@rdivide, 100 * A, A(:, 1)) - 100;

What your code is doing is taking each column of your matrix A and dividing by the first column of it. You are doing some extra scaling, such as multiplying all of the columns by 100 before dividing, and then subtracting after. bsxfun internally performs broadcasting which means that it will temporarily create a new matrix that duplicates the first column for as many columns as you have in A and performs an element-wise division. You can complete your logic by pre-scaling the matrix by 100, then subtracting by 100 after.

With MATLAB R2016b, there is no need for bsxfun and you can do it natively with arithmetic operations:

B = (100 * A) ./ A(:,1) - 100;
like image 93
rayryeng Avatar answered May 10 '26 12:05

rayryeng



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!