For loop only accesses the last element in an array

Hi all,
I have an array CHANNEL[10 58 27], and I want my for loop to access all three elements. However, right now when I look at the value of di in my workspace, it says 27, so I'm assuming that it is only accessing the last element of the array.
How should I fix the code so that di accesses all three elements in the array?
for di=CHANNEL(1,:)
%load (append('210603_bare-210727-182826','ch',string(di)))
neural = timetable(RawData,'SampleRate',fs);
neural.Properties.VariableNames{1} = 'raw';
neural.Properties.VariableUnits{1} = 'Volts';
HighPass = 300;
LowPass = 5000;
[Z, P, K] = butter(5, [HighPass LowPass]/(fs/2), "bandpass");
sos = zp2sos(Z, P, K);
neural.raw = double(neural.raw);
neural.spikes = sosfilt(sos,RawData);
for idx=1:length(CHANNEL)
figure;
nexttile;
plot(neural.Time,neural.spikes(:,idx))
end
xlim([duration(0,init_mn,init_s,init_ms) duration(0,end_mn,end_s,end_ms)])
ylim([-1e-4 1e-4])
end

4 件のコメント

Stephen23
Stephen23 2021 年 8 月 6 日
"so I'm assuming that it is only accessing the last element of the array."
Rather than assuming things, you could check what the loop is doing:
for di = CHANNEL(1,:)
disp(di)
..
end
"However, right now when I look at the value of di in my workspace, it says 27..."
Which is exactly what I would expect the value of di to have after the loop has finished:
  1. on the 1st loop iteration it has value 10
  2. on the 2nd loop iteration it has value 58
  3. on the 3rd loop iteration it has value 27
The value from the last iteration remains in the workspace after the loop has finished.
Soeun Lee
Soeun Lee 2021 年 8 月 6 日
Thank you for your comment. If di is accessing all three elements as you mentioned, then could you please let me know why I am obtaining three identical graphs when I plot plot(neural.Time,neural.spikes(:,idx))?
Stephen23
Stephen23 2021 年 8 月 6 日
@Soeun Lee: it might have something to do with your looping over the same vector in nested loops:
for di=CHANNEL(1,:)
...
for idx=1:length(CHANNEL)
figure;
nexttile;
plot(neural.Time,neural.spikes(:,idx))
end
...
end
I very much doubt that that nested loop does what you expect or need.

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

回答 (0 件)

カテゴリ

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

製品

質問済み:

2021 年 8 月 6 日

コメント済み:

2021 年 8 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by