Reputation: 71
I have a vector, for example:
test = [1 2 -3 -4 -5 -8 1 2 3 -5 -9 -2 3 2 1];
And I would like to detect the changing of plus/minus sign in this vector. I need to detect only the changing of signs. For example, if the sign changed, so print on the command line: 'Change'.
Thank you for your help.
Upvotes: 0
Views: 226
Reputation: 525
As @lodestar said, there are many ways to do this. If you are looking for displaying something at the command prompt then you should look at disp
. For instance:
>> arrayfun(@(x)disp(['Change at ', num2str(x+1)]),find((test(1:end-1).*test(2:end))<0))
Change at 3
Change at 7
Change at 10
Change at 13
Upvotes: 1
Reputation: 198
There are many possibilities to do this. One of them that doesn't involve for
loops is:
test = [1 2 -3 -4 -5 -8 1 2 3 -5 -9 -2 3 2 1] % Original vector
signs = sign(test); % Get vector signs
diff = signs(2:end) - signs(1:end-1); % Compute difference between
% successive values
indices = find(diff ~= 0) + 1; % Get indices of sign changes
The variable indices
then has the values 3, 7, 10 and 13.
Upvotes: 3