3

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?

2
  • 2
    The outer loop over ii doesn't do anything, so you can just divide the entire matrix by the first column. Commented Apr 25, 2017 at 16:37
  • @beaker I just edited the question to make it clearer Commented Apr 25, 2017 at 16:43

1 Answer 1

5

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.