Note: 'functionValues' has the same dimension as 'u' and 'v'. In fact I wish to sum up values of 'functionValues' for different 'R' at each position of 'functionValues'.
How to avoid using 'for' loop
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
'u' and 'v' are 401*401 matrices and 'R' is a 401*1 matrix. I have a function which gets 'u' and 'v' vectors and one value of 'R' per iteration and calculates the value of the function. Then after that, I have to sum all these values to get the final result. I wish to achieve my goal without using 'for' loop. Is it possible?
Example:
% Initialize 'u', 'v', and 'R' matrices
u = ...; % 401x401 matrix
v = ...; % 401x401 matrix
R = ...; % 401x1 matrix
functionValues =zeros(401,401);
% Calculate the values of the function for each element
for i=1:numel(R)،
functionValues = functionValues + calculateValue(u, v, R(i)); % 401x401 matrix
end
In fact I wish to avoid using 'for' loop to increase running speed.
Antworten (2)
Image Analyst
am 22 Okt. 2023
Just modify youir calculateValue() so that it takes multiple values of R (can handle R being a vector) and returns a vector instead of a single scalar number. Then just call the function -- no for loop needed.
2 Kommentare
Image Analyst
am 22 Okt. 2023
Then why not
theSum = 0;
for k = 1 : numel(R)،
theSum = theSum + calculateValue(u, v, R(k)); % 401x401 matrix
end
And I agree with @Dyuman Joshi with only a few iterations (401*401) you'd most likely not notice any difference at all. It might be a different story if you had hundreds of millions of elements.
Dyuman Joshi
am 22 Okt. 2023
However, this assumes that calculateValue() can be vectorized.
And if it can be, I doubt if you will see any noticeable speed increase by using vectorization instead of using a for loop.
5 Kommentare
Dyuman Joshi
am 22 Okt. 2023
Bearbeitet: Dyuman Joshi
am 25 Okt. 2023
@moh mor, is there still a problem?
Does it work properly? And did you check the speed of the two methods for comparison?
Siehe auch
Kategorien
Mehr zu Matrix Indexing 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!