Is there anyway to make a for loop variable global?
10 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
I am using a for loop to define a variable, and I then want to use this variable outside of the loop to continue my analysis. However, when I try to use the variable outside of the loop matlab tells me that the variable does not exist. Here is my example:
for j=1:length(ev)
if ismember(1029,ev(j).Code); %finding places in the code where the event code is 1029
time=ev(j).Time(1); %filling in start and stop time into the variable 'time', these are relative time
time=time(1); %this is the start time of the 1st 1029 code
end
end
I want to use the variable time outside of the loop but matlab doesn't recognize the variable. I have tried creating an empty array before the for loop to see if it would populate, but that didn't work. Is there any way to fix this?
2 Commenti
Allen
il 25 Mag 2021
Where in relation to this loop are you trying to use your time variable? Are you trying to use it within the same script or function, or outside of your main script or function?
Risposte (1)
DGM
il 25 Mag 2021
If the variable time is not defined after the loop exits, then that's because it was never defined in the loop. Ask yourself what happens if
ismember(1029,ev(j).Code)
is never true?
In what case would it never be true? Are there any values which are equal to 1029? Are they exactly equal to 1029? Is ev.Code floating point?
Make sure that the variable is defined even when that case isn't true.
Also, it looks like you're overwriting time anyway, so I don't know what you expect.
3 Commenti
DGM
il 26 Mag 2021
On what lines is the variable time defined? If the only lines are those shown, then the nonexistence of the variable indicates that the test was false. The variable is not cleared unless you're clearing it or resetting it explicitly in some lines that you aren't showing. There is no need for global variables to access a variable outside the scope of a loop. If it's not available, it's because it's not being defined.
for x = 1:2
if x==2
y = 1000;
end
end
y
clearvars;
for x = 1:2
if x==3
y = 1000;
end
end
y
As to why it's not being defined, I could guess all day, but you're the only one who knows what your code and data look like.
Steven Lord
il 26 Mag 2021
Every trial contains a 1029 code
Every trial is supposed to contain a 1029 code. Trust but verify. Assign some placeholder value that is never going to be a valid value for your time variable, like NaN, to your time variable before the start of your for loop. Check after the loop and if the time variable is still NaN then your assumption (every trial contains a 1029 code) was not valid.
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!