Filter löschen
Filter löschen

Infinite for loop getting stuck. Creating a new column containing a variable.

1 Ansicht (letzte 30 Tage)
Hi, I am trying to generate a new column variable within a table which is conditional on 2 other values. The for loop I am using to generate it is getting stuck, however. It is generating the right values for me but just gets stuck and goes through the column over and over again. Any help would be appreciated:
data.signal = zeros(size(data.NAPMPMIIndex));
for indx=1:numel(data.NAPMPMIIndex)
if(data.NAPMPMIIndex(indx) > 50 & data.AboveMA(indx)> 0.5)
data.signal(indx) = 0.5
elseif(data.NAPMPMIIndex(indx) > 50 & data.AboveMA(indx)< 0.5)
data.signal(indx) = -0.5
elseif(data.NAPMPMIIndex(indx) < 50 & data.AboveMA(indx)> 0.5)
data.signal(indx) = 1
else
data.signal(indx) = -1;
end
end
  10 Kommentare
Adam Danz
Adam Danz am 29 Aug. 2019
I ran the code in your question using the data attached to your comment above. The loop is not getting stuck nor is it repeating the same column as you described. The loop runs as it should.
To confirm that, run this version below. The the only differences are
  • semicolons are used to suppress unnecessary output.
  • a counter "c" is used to count each iteration of the for-loop and the count is displayed so you can visually confirm that the loop has the expected 714 iterations.
load spxpmi2
data.signal = zeros(size(data.NAPMPMIIndex));
c = 0;
for indx=1:714
c = c+1;
disp(c)
if(data.NAPMPMIIndex(indx) > 50 & data.AboveMA(indx)> 0.5)
data.signal(indx) = 0.5;
elseif(data.NAPMPMIIndex(indx) > 50 & data.AboveMA(indx)< 0.5)
data.signal(indx) = -0.5;
elseif(data.NAPMPMIIndex(indx) < 50 & data.AboveMA(indx)> 0.5)
data.signal(indx) = 1;
else
data.signal(indx) = -1;
end
end
nskel
nskel am 29 Aug. 2019
ah, thanks very much.
I'm quite new to this but that is very much a rookie error
:-)

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Andrei Bobrov
Andrei Bobrov am 27 Aug. 2019
kk = [data.NAPMPMIIndex > 50, data.AboveMA > .5];
g = findgroups(kk(:,1),kk(:,2));
a = [-1;1;-.5;.5];
data.signal = a(g);
  3 Kommentare
Andrei Bobrov
Andrei Bobrov am 30 Aug. 2019
Hi Nskel! Maybe we will accept this answer, huh? Excuse me.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Startup and Shutdown finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by