Vectorizing a for loop in MATLAB
In MATLAB, given a matrix A
, I want to create a matrix B
containing the elements of the matrix A
as a percentage of the first elements of the column. 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 one line using vectorization? Could it arrayfun
be helpful in this matter?
source to share
Use bsxfun
in this case:
B = bsxfun(@rdivide, 100 * A, A(:, 1)) - 100;
What your code does is take each column of your matrix A
and divide it by the first column. You do additional scaling, such as multiplying all columns by 100 before dividing and then subtracting after. bsxfun
does the translation internally, which means it will temporarily create a new matrix that duplicates the first column for as many columns as you have in A
, and does elemental 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 using arithmetic operations:
B = (100 * A) ./ A(:,1) - 100;
source to share