Vectorize a code involving multiple loops commands
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Askeladden2
am 10 Aug. 2020
Kommentiert: Askeladden2
am 10 Aug. 2020
Dear All Community members,
I have created a code involving three loops and a while command. I want to vectorize the code because it involves combining large matrices and is far too slow to run.
A short explanation;
I want to estimate a result using a mathematical operation combining three matrices that corresponds to a fixed value.
I.e.; I run a range of dummy values ("x") through a mathematical formula based on two large matrices ("a" and "b") and further multiply these results with another matrix "c".
I create a new matrix established by the dummy values and the corresponding sums above. (I can perhaps avoid this matrix using vectorization?)
The result is found by the dummy results when the corresponding sum is equal to the fixed value "d".
A simple example of the code is given below:
x = [0:0.1:10];
a=[2 1; 0.5 0.25];
b=[500 200; 300 250];
c=[0.25 0.35; 0.15 0.25];
d=[0.5];
for k = 1:length(x);
for i = 1:length(a)
for j = 1:length(a)
ab(i,j) = exp(-exp(-((x(k)-a(i,j)*sqrt(2*log(b(i,j))))/(a(i,j)/(sqrt(2*log(b(i,j))))))));
abc(i,j) = ab(i,j) * c(i,j);
end
end
%sum
abcSum = sum(sum(abc));
x(k);
TotSum(k) = abcSum;
end
i = 1;
%target d
while (1 - TotSum(i)) > (d)
i = i + 1;
end
%Result
Result = x(i);
The results shal be 3.2.
I appreciate all help and tips.
Thanks in advance!
2 Kommentare
Stephen23
am 10 Aug. 2020
Bearbeitet: Stephen23
am 10 Aug. 2020
"I want to vectorize the code because it involves combining large matrices and is far too slow to run."
Why do you think that vectorized code would be faster? Vectorizing code involving large array is liable to have the opposite effect: it could easily make your code slower due to the generation of large intermediate arrays.
In any case, the complete lack of array preallocation shows that your current loops are not optimised at all, you are likely to get much better returns for your time by improving your existing code (e.g. preallocate those arrays, run the profiler, replace the while loop with find, etc.).
Akzeptierte Antwort
Bruno Luong
am 10 Aug. 2020
Bearbeitet: Bruno Luong
am 10 Aug. 2020
x = [0:0.1:10];
a=[2 1; 0.5 0.25];
b=[500 200; 300 250];
c=[0.25 0.35; 0.15 0.25];
d=[0.5];
X = reshape(x,1,1,[]);
AB = exp(-exp(-((X-a.*sqrt(2*log(b)))./(a./(sqrt(2*log(b)))))));
ABC = AB.*c;
TotSum = reshape(sum(ABC,[1 2]),1,[]);
i = find(1 - TotSum <= d, 1, 'first')
Result = x(i)
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!