How to divide a matrix by each column of an array, need your help!

1 view (last 30 days)
I would like to divide each column by an array. for instance,
clear
clc
A(1:5,1:5) = 5;
B= [1 2 3 4 5 ]
C=A/B
the answer I am looking for is
5/1 5/2 5/3 5/4 5/5
5/1 5/2 5/3 5/4 5/5
5/1 5/2 5/3 5/4 5/5
5/1 5/2 5/3 5/4 5/5
5/1 5/2 5/3 5/4 5/5
I need a much faster way than A(1)/B(1)
any help is much appreciated!

Answers (1)

Star Strider
Star Strider on 29 Nov 2015
The bsxfun function is perfect for this:
A(1:5,1:5) = 5;
B= [1 2 3 4 5 ];
C = bsxfun(@rdivide, A, B)
format rat
C
Results:
C =
5 2.5 1.6667 1.25 1
5 2.5 1.6667 1.25 1
5 2.5 1.6667 1.25 1
5 2.5 1.6667 1.25 1
5 2.5 1.6667 1.25 1
C =
5 5/2 5/3 5/4 1
5 5/2 5/3 5/4 1
5 5/2 5/3 5/4 1
5 5/2 5/3 5/4 1
5 5/2 5/3 5/4 1

Tags

Community Treasure Hunt

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

Start Hunting!