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.

 채택된 답변

Stephen23
Stephen23 2017년 11월 14일
편집: Stephen23 2017년 11월 14일

1 개 추천

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

Lisa Jones
Lisa Jones 2017년 11월 14일
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 2017년 11월 14일
편집: Stephen23 2017년 11월 14일
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.
Lisa Jones
Lisa Jones 2017년 11월 14일
Thank you so much for your help, answer now accepted.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기

태그

질문:

2017년 11월 14일

댓글:

2017년 11월 14일

Community Treasure Hunt

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

Start Hunting!

Translated by