How to append elements into a 2D cell array

조회 수: 31 (최근 30일)
Justin Sung
Justin Sung 2019년 7월 4일
답변: xi 2019년 7월 4일
Hi all,
What I want to do is to append certain elements to a row of a 2D cell array. The code I have so far is really close to what I want and looks like this:
GM = readmatrix('file1');
[rowGM, colGM] = size(GM);
SM = readmatrix('file2');
[rowSM, colSM] = size(SM);
for index = 1:rowGM
for i = 1:rowSM
if ( strcmp(SM{i, 3}, GM{index, 1}) && isequal(index, str2double(SM{i, 1})) )
GM{index, end + 1} = SM{i, 1}; % kinda bad
end
end
end
What is happening here is that I have 2 input matrices read from file1 and file2. they are saved into variables GM and SM respectively. Based on some strcmp and isequal operations, I append whatever element currently being processed in SM to the corresponding row in GM. I've attatched a pictures to show what GM and SM look like. I've obmitted some sensitive data in the pictures and code, probably making the code above full of errors and the pictures inconsistent for privacy reasons. If it becomes necessary to help aid understanding and answering, I will consider releasing some of the omitted data.
The matrix GM looks like this:
The matrix SM looks like this:
Hopefully, this helps make the code more understandable. I'm checking whether:
  1. id_string in the 3rd column of SM matches the id_string of the 1st column of GM
  2. if the row number of GM matches the row identifier number, the 1st column of SM
If both of these conditions are satisfied, then I append the row identifier number to the corresponding row in GM.
I saw this post and tehnically, it works with my other code (currently I have this solution in my code above), but boy is not good for what I want to do. The final GM I get looks like this:
The ideal GM that I am looking for looks like this:
Is there any way I can write something that has an appending-behavior like this? Transpose? I'd appreciate any feedback on this.
Thanks in advance.
  댓글 수: 1
KSSV
KSSV 2019년 7월 4일
It looks like you need not to use loop to achieve this. You may use ismember and get what you want. We can work on it if we data in hand.

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

채택된 답변

xi
xi 2019년 7월 4일
Don't use "end", because it keeps getting larger when you append. Need to reset it in between the two loops. try below
......
for index = 1:rowGM
count = 0;
for i = 1:rowSM
if ( strcmp(SM{i, 3}, GM{index, 1}) && isequal(index, str2double(SM{i, 1})) )
count = count + 1;
GM{index, count + 1} = SM{i, 1}; % kinda bad
end
end
end

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by