Array notation instead of iterative loop for difference equation

Hi, I have somehow a difference equation and wanted to improve the speed of my code and calculate it directly through arrays instead of an iterative loop.
I have a container that is continuously filled. It is emptied at certain times.
I would like to have the mass at each time step of the container.
With an iterative loop I calculated it:
% Dummy values for the incomming mass
m_new = randi(50,288,1);
% Time slots to empty the container
m_empty = false(size(m_new));
m_empty([60,60+96, 60+2*96]) = true;
% Use the mass of the previous time step unless the container has been emptied
contents_remaining = xor(true, m_empty);
% Initializing my array for the loop
mm = zeros(size(m_new));
% Initialize my array with a start value
mm(1) = 300;
% For each time step, calculate the content from the previous time step and the newly added mass.
for i = 1:size(m_new,1)-1
mm(i+1) = mm(i) * contents_remaining(i) + m_new(i);
end
Is it possible to perform this calculation without a for loop?
Unfortunately, I have not come up with a satisfactory result and hope you can help me to avoid the for loop.

6 件のコメント

Dyuman Joshi
Dyuman Joshi 2023 年 11 月 13 日
m_new = randi(50,size(m_new));
Something is not right here.
Also, given the operations performed in the code above, it seems mm should be prellocated as a vector, instead of a square matrix.
Torsten
Torsten 2023 年 11 月 13 日
Julian
Julian 2023 年 11 月 14 日
編集済み: Dyuman Joshi 2023 年 11 月 14 日
@Dyuman Joshi I have mixed up the line of m_new and m_empty
@Torsten Ok, that means I wasn't on the wrong track, but there is no better solution to the problem.
Dyuman Joshi
Dyuman Joshi 2023 年 11 月 14 日
I don't see a problem with this approach.
Stephen23
Stephen23 2023 年 11 月 14 日
"Is it possible to perform this calculation without a for loop?"
Why?
Torsten
Torsten 2023 年 11 月 14 日
編集済み: Torsten 2023 年 11 月 14 日
Ok, that means I wasn't on the wrong track, but there is no better solution to the problem.
Yes, recursions are hard (or even impossible ?) to vectorize.

サインインしてコメントする。

回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

製品

リリース

R2023a

質問済み:

2023 年 11 月 13 日

編集済み:

2023 年 11 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by