MATLAB: Condition on two arrays

array

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

Best Answer

Since it now appears that you care only about those elements of z that also lie in y, the solution is simple. The code you wrote will ALMOST work, IF you save the results properly.
For example, this should work:
sumelems = zeros(size(x));
for i = 1:length(x)
sumElems(i) = sum(z==x(i)&y==1);
end
Note that I used a &, NOT the && operator. && is used only in tests like an if statement, or in a while statement.
Could I have written the above more simply, without using a loop? Yes. But why bother writing code that will be far less readable, for a tiny problem? Don't pre-optimize code just because a solution may seem more "elegant".