Effacer les filtres
Effacer les filtres

Loop is not reading from the first value in the array?

1 vue (au cours des 30 derniers jours)
Jasmine Karim
Jasmine Karim le 8 Août 2018
Commenté : Jasmine Karim le 9 Août 2018
I have a loop that is transferring data between two arrays, however, I'm not sure why it is not reading from the very first and last values. The first array (arrayA) looks like:
{'7'} {'ans'} {[1]}
{'7'} {'ans'} {[2]}
{'7'} {'ans'} {[3]}
second array (arrayB) looks like:
{'7' } {[101]} {[1]}
{'ans'} {[278]} {[1]}
{'7' } {[299]} {[2]}
{'ans'} {[300]} {[2]}
{'7' } {[432]} {[3]}
{'ans'} {[467]} {[3]}
With the following loop, IF the value in arrayA{a,3} matches that in arrayB{b,3}, i want the FIRST matching value to appear in arrayB{b,4} and the SECOND matching value to appear in arrayB{b,5}.
for a = 1:length(arrayA)
for b = 1:length(arrayB)
if arrayA{a,3}==arrayB{b,3}
arrayA{a,4} = arrayB{b,2};
arrayA{a,5} = arrayB{(b+1),2};
end
end
end
Right now, it looks like:
{'7'} {'ans'} {[1]} {[278]} {[299]}
{'7'} {'ans'} {[2]} {[300]} {[432]}
{'7'} {'ans'} {[3]} {[467]} {[467]}
What I would like however would be:
{'7'} {'ans'} {[1]} {[101]} {[278]}
{'7'} {'ans'} {[2]} {[299]} {[300]}
{'7'} {'ans'} {[3]} {[432]} {[467]}
  2 commentaires
Rik
Rik le 8 Août 2018
What is the goal of this code? What are you trying to achieve? Also, (b-1)+1 is just b, so is that a typo?
I think I would use ismember(arrayA,arrayB) to get a list of valid positions, but that is just a gut feeling without knowing a bit more about your goal and what sort of data to expect.
Jasmine Karim
Jasmine Karim le 9 Août 2018
Thanks for asking for clarification, I have posted a sample dataset to better explain what I am trying to achieve

Connectez-vous pour commenter.

Réponse acceptée

Fangjun Jiang
Fangjun Jiang le 9 Août 2018
It is because third column in B has duplicated values. For example, the result of the first loop (b=1) in the "for b = 1:length(arrayB)" loop is over-written by the second loop (b=2)
  5 commentaires
Fangjun Jiang
Fangjun Jiang le 9 Août 2018
for a = 1:size(arrayA,1)
Col=3;
for b = 1:size(arrayB,1)
if arrayA{a,3}==arrayB{b,3}
Col=Col+1;
arrayA{a,Col} = arrayB{b,2};
end
end
end
Note that size() is better than length() for your case.
Jasmine Karim
Jasmine Karim le 9 Août 2018
Ah, I had not used size instead of length before. Thank you!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by