Filter löschen
Filter löschen

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

1 Ansicht (letzte 30 Tage)
Jasmine Karim
Jasmine Karim am 8 Aug. 2018
Kommentiert: Jasmine Karim am 9 Aug. 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 Kommentare
Rik
Rik am 8 Aug. 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 am 9 Aug. 2018
Thanks for asking for clarification, I have posted a sample dataset to better explain what I am trying to achieve

Melden Sie sich an, um zu kommentieren.

Akzeptierte Antwort

Fangjun Jiang
Fangjun Jiang am 9 Aug. 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 Kommentare
Fangjun Jiang
Fangjun Jiang am 9 Aug. 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 am 9 Aug. 2018
Ah, I had not used size instead of length before. Thank you!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by