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

1 view (last 30 days)
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 Comments
Rik
Rik on 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 on 9 Aug 2018
Thanks for asking for clarification, I have posted a sample dataset to better explain what I am trying to achieve

Sign in to comment.

Accepted Answer

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

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!