perform matrix operation without for loop

2 Ansichten (letzte 30 Tage)
SChow
SChow am 25 Sep. 2020
Kommentiert: Ameer Hamza am 25 Sep. 2020
I have a matrix (exp_data) of size 25000*45000. I need to perform the following operations as in the code, however with the for loop it takes ~4 hours to operate,
beta is a set of 3 values, for which I need to perform the operations. beta=[0.1, 0.04, 0.6]
any help is much appreciated
for m=1:3
for i=1:25000
for j=1:45000
if exp_data(i,j)>1.5;
xes(i,j)=exp(beta(m).*(exp_data(i,j)));
else xes(i,j)=1;
end;
end
end;
xe(:,:,m)=xes;
end;

Akzeptierte Antwort

madhan ravi
madhan ravi am 25 Sep. 2020
Bearbeitet: madhan ravi am 25 Sep. 2020
xe = exp(reshape(beta, 1, 1, []) .* exp_data) .* (exp_data > 1.5) + 1 * (exp_data <= 1.5);
% use bsxfun() for implicit expansion in older versions
xe = exp(bsxfun(@times, reshape(beta, 1, 1, []), exp_data)) .* (exp_data > 1.5) + 1 * (exp_data <= 1.5);
  1 Kommentar
Ameer Hamza
Ameer Hamza am 25 Sep. 2020
Not sure if MATLAB realizes that when (exp_data > 1.5) is 0, it should avoid the corresponding calculations in exp(reshape(beta, 1, 1, []); otherwise, that is just a waste of computation. 🤔

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Ameer Hamza
Ameer Hamza am 25 Sep. 2020
Bearbeitet: Ameer Hamza am 25 Sep. 2020
Following code is equivalent
xe = zeros([size(exp_data) numel(beta)]);
mask = exp_data > 1.5;
for m = 1:numel(beta)
xes = ones(size(exp_data));
xes(mask) = exp(beta(m).*(exp_data(mask)));
xe(:,:,m) = xes;
end
Not sure if there are any speed improvements since JIT compiler is already claimed to be working very well.
  2 Kommentare
madhan ravi
madhan ravi am 25 Sep. 2020
I belive your last line should be:
xe(:,:,m) = xes;
Ameer Hamza
Ameer Hamza am 25 Sep. 2020
Yes!! Thanks for correction.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by