How to vectorize this for loop

Hello.Here's my codes from a program.I want to improve its efficiency,so I try to vectorize for loop.But I'm just a beginner in coding.I can't figure it out.Hope anyone who mastering in Matlab can help me to solve this.Thanks.
K = 10;
N = 10;
M = 10;
X(1:10,1:10) = 1;
seed_num = 123;
rng(seed_num);
B = abs(randi([1,100],M,N))
a = [];
m = [];
for l = 1:K
for j = 1:N
for k = 1:M
num = X(l,k)*B(k,j);
a = [a,num];
end
m = [m,max(a)];
a = [];
end
end
S = sum(m);

 Accepted Answer

Stephen23
Stephen23 on 5 Jun 2018
Edited: Stephen23 on 5 Jun 2018
Method one: If X only contains ones (like in your example)
S = K*sum(max(B,[],1))
Method two: If X contains values other than one, then you could use this:
M = max(bsxfun(@times,B,permute(X,[2,3,1])),[],1);
S = sum(M(:))
Explanation:
The original code is very inefficient, and it needs a lot of revision. For example, this loop:
a = []
...
for k = 1:M
num = X(l,k)*B(k,j);
a = [a,num];
end
just puts the j-th column into a variable a (note all X are one), so this is equivalent to
a = B(:,j);
But then the only operation on a is to have max applied, so there is no point doing this or each column separately because we can do this all at once using
max(B,[],1)
Taking the sum is then trivial. The original code repeats this K times, inefficiently concatenating new max value onto m each time, so we can just multiply that sum by K to get exactly the same output.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 5 Jun 2018

Edited:

on 5 Jun 2018

Community Treasure Hunt

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

Start Hunting!