condition on two arrays
이전 댓글 표시
Hi,
Given three arrays x,z and y:
z = [5,5,7,7,7,11,15,15,29,29,29]
y = [1,2,3,2,1,1,1,1,2,3,1]
x = [5,7,29]
x contains some elements of z uniquely. For these elements, I wanted to count how often each of their appearance in z is accompanied with a "1" for the same index in y. For instance z contains two "5", at index 1 and at index 2, but only index 1 in y is equal to 1, so the result should be "1".
I coded the following, but this gives me completely wrong results:
for i = 1:length(x)
sumElems = sum(z==x(i)&&y==1)
end
댓글 수: 3
John D'Errico
2017년 12월 12일
Why would you extend the length of the loop to be length(y)? In fact, that loop should generate an error as you wrote it, since length(y) is 11, and you index x(i).
There are only 3 distinct values in x, and you claim to be only interested in the members of x.
Yes, there will surely be a solution. But you need to be clear about the problem you are trying to solve.
MiauMiau
2017년 12월 12일
John D'Errico
2017년 12월 12일
편집: John D'Errico
2017년 12월 12일
Are you interested ONLY in the elements that lie in x? If you are, then why are you looping over the length of y?
Note that there are some elements of z that are not members of x, yet they too have a corresponding 1 in y.
As I said, the code that you wrote originally will fail to run at all, so we cannot use that to infer what you are looking to get. (I do see that you have now changed the code to loop only over the length of x.)
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!