MATLAB: Failed to create signal form successive values

for;if;signal;indicator

hi,
I'm trying to create a signal of 1 and -1 with a for loop but getting an error of "Subscript indices must either be real positive integers or logicals." My code is like this
for i=1:length(data)
if (MACD(i-1)>0) && (MACD(i)<0)
s(i,:)=-1; % Sell (short)
end
if (MACD(i-1)<0) && (MACD(i)>0)
s(i,:)=1; % buy (long)
end
end
Could you tell me where is the mistake please.

Best Answer

You can do it without the loop:
zci = @(v) find(v(:).*circshift(v(:), [-1 0]) <= 0); % Returns Approximate Zero-Crossing Indices Of Argument Vector
MACD = rand(1, 25)-0.5; % Create ‘MACD’ Data
zx = zci(MACD); % Find Zero-Crossings
zx = zx(1:end-1); % Eliminate Wrap-Around ‘End Effect’
sx = sign(MACD(zx+1)); % Set Signs Of Zero-Crossings
s = zeros(size(MACD)); % Define ‘s’
s(zx+1) = sx; % Insert Sign Vector Into ‘s’
My code uses the ‘zci’ anonymous function to return the zero-crossing indices of your ‘MACD’ vector, then assigns the sign by looking at the next value in the vector in the ‘sx’ vector. It then creates ‘s’ and assigns ‘sx’ to the appropriate positions in it to create the desired output for ‘s’.