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".
Best Answer