For loop goes longer than expected.

3 ビュー (過去 30 日間)
Hendrik2k1
Hendrik2k1 2020 年 5 月 29 日
コメント済み: Hendrik2k1 2020 年 5 月 29 日
Dear all,
I want to extract a part of a colomn vector into another vector. I tried the following:
startSample = Fs*startTime; % Becomes 112800
stopSample = Fs*stopTime; % Becomes 152800
y5s_unfiltered = zeros(stopSample-startSample,1);
for i = startSample:stopSample
y5s_unfiltered(i,1) = y(i,1); % y is the source vector and y5s_unfiltered the destination vector
end
I would expect the for loop to go 40000 times with i in the beginning is 112800 and in the end it is 152800. But unfornately the vector y5s_unfiltered becomes a 112800x1 double vector.So it grows beyond it expected 40000x1 size.
Can you help me what is the cause for this behaviour?

採用された回答

Stephen23
Stephen23 2020 年 5 月 29 日
"Can you help me what is the cause for this behaviour?"
Because that is the indexing that you used.
You defined the loop iterator to go from 112800 to 152800, and you used those values as indices into y5s_unfiltered, so the last index of y5s_unfiltered that you allocate to will be 152800. MATLAB will simply expand that vector to suit those indices, which won't be very efficient.
The solution is to loop like this:
V = startSample:stopSample;
N = numel(V);
y5s_unfiltered = zeros(N,1);
for k = 1:N
y5s_unfiltered(k,1) = y(V(k),1);
end
Or use MATLAB's basic indexing abilities and avoid the loop entirely:
y5s_unfiltered = y(startSample:stopSample);
  1 件のコメント
Hendrik2k1
Hendrik2k1 2020 年 5 月 29 日
Ummmmg yeah, you are right. I hab to add (i-startSample+1) at the destination vector. Ok Thanks

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

その他の回答 (1 件)

Alan Stevens
Alan Stevens 2020 年 5 月 29 日
Try
for i = 1:(stopSample-startSample+1)
y5s_unfiltered(i,1) = y(i,1); % y is the source vector and y5s_unfiltered the destination vector
end
  1 件のコメント
Hendrik2k1
Hendrik2k1 2020 年 5 月 29 日
This also works. Thanks for clarification.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by