Adding numbers in a matrix to equal zero

Please help, I need to go through my matrix to find if two numbers following one another that equal zero, for example if I had:
4 5 -5 7
1 0 -1 9
2 4 -4 0
This example gives me the 5 and -5 that equal 0. The numbers must be next to one another in the row but I need the answer to say yes just one time if it happens anywhere in the matrix or no if it doesn't appear at all.
Sorry if I haven't explained this well, I've been working on it for so long and have probably confused myself.

 Risposta accettata

Stephen23
Stephen23 il 14 Nov 2017
Modificato: Stephen23 il 14 Nov 2017
This is MATLAB, so there is no need to write ugly code with lots of loops and ifs when it is so much simpler and neater to operate on the whole array at once. Assuming that you only want to add two adjacent values, then this will work:
>> X = [4,5,-5,7;1,0,-1,9;2,4,-4,0]
X =
4 5 -5 7
1 0 -1 9
2 4 -4 0
>> idx = ~(X(:,1:end-1)+X(:,2:end)) % locations
idx =
0 1 0
0 0 0
0 1 0
>> any(idx(:)) % anywhere in matrix
ans = 1
If you want to add more than two values or an arbitrary number of values then you will need to specify this and use a different method.

3 Commenti

This works lovely, thank you so much. Is there a way I can ask Matlab to display it as yes/no rather than 1 or 0?
Stephen23
Stephen23 il 14 Nov 2017
Modificato: Stephen23 il 14 Nov 2017
C = {'no','yes'};
C{1+any(idx(:))}
Remember to accept the answer that best resolves your original question: this is the easiest way for you to thank the volunteers who help you.
Thank you so much for your help, answer now accepted.

Accedi per commentare.

Più risposte (0)

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by