condition on two arrays
Mostra commenti meno recenti
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 Commenti
John D'Errico
il 12 Dic 2017
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
il 12 Dic 2017
John D'Errico
il 12 Dic 2017
Modificato: John D'Errico
il 12 Dic 2017
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.)
Risposta accettata
Più risposte (0)
Categorie
Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!