フィルターのクリア

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 Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by