필터 지우기
필터 지우기

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

조회 수: 1 (최근 30일)
Jasmine Karim
Jasmine Karim 2018년 8월 8일
댓글: Jasmine Karim 2018년 8월 9일
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
Rik
Rik 2018년 8월 8일
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 2018년 8월 9일
Thanks for asking for clarification, I have posted a sample dataset to better explain what I am trying to achieve

댓글을 달려면 로그인하십시오.

채택된 답변

Fangjun Jiang
Fangjun Jiang 2018년 8월 9일
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
Fangjun Jiang
Fangjun Jiang 2018년 8월 9일
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 2018년 8월 9일
Ah, I had not used size instead of length before. Thank you!

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by