Replacing for loop in order to decrease run time

1 次查看(过去 30 天)
I'm trying to add the difference between 2 arrays (if A(i) > B(i)) to the next element of array A. I'm unsure how to decrease the time needed to run this code (it'll be integrated using ode45)
for i = 1:length_chain_classes
if Rate_array(i) > ChainLengths(i) %% if more glucose gets designated to class than it can accept, at surplus to next class
Surplus_g1p = Rate_array(i) - ChainLengths(i);
Rate_array(i) = ChainLengths(i);
if i ~= length(Rate_array) %% voids surplus only if at last class
Rate_array(i+1) = Rate_array(i+1) + Surplus_g1p;
end
end
end
I'm unsure how to reference the next/previous value in a vector without using a for loop
  2 个评论
Tommy
Tommy 2020-4-24
It seems like the order in which this loop runs does matter, as you might change Rate_array(i+1) on one iteration, thereby changing the result of Rate_array(i) > ChainLengths(i) on the next iteration. Therefore, vectorizing this code may leave you with incomplete results. You could solve the issue by rerunning the code until you know you're done, demonstrated below using sample A and B vectors:
A = randi(10,10,1);
B = randi(10,10,1);
i = A>B;
while any(i)
sg = A-B;
A(i) = B(i);
A([false; i(1:end-1)]) = A([false; i(1:end-1)]) + sg([i(1:end-1); false]);
i = A>B;
end
There may be a better way. This at least shows how you can "reference the next/previous value in a vector without using a for loop."
Bastiaan
Bastiaan 2020-4-28
Thanks! This code seems to improve the performance by a bit

请先登录,再进行评论。

回答(1 个)

Athul Prakash
Athul Prakash 2020-4-30
Hi Bastiaan,
I think this way you can solve it. Below is how yo
D = A(1, end-1) - B(1, end-1);
D = [0; D] % ';' Assuming A & B are col vectors. Otherwise use ','
A = A + D;
Hope it helps!

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by