AJMA
AJMA

Reputation: 1194

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?

Upvotes: 3

Views: 62

Answers (1)

rayryeng
rayryeng

Reputation: 104555

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;

Upvotes: 5

Related Questions