Finding similar values in two different cell arrays and comparing them?

조회 수: 17 (최근 30일)
Atiqah Zakirah
Atiqah Zakirah 2017년 5월 26일
답변: Jan 2017년 5월 26일
I have 2 separate cell arrays (alight and board), both containing a column for name, hour, and passenger count. I need to find where the name and hour is equal to each other in both columns, and take the corresponding passenger count of both and then find the difference in passenger count. That difference should then be stored in another column in either one of the cell arrays. This is my code but it has an "too many input arguments" and "error using ==" error in line "index = find(board{:,1} == stn & board{:,2} == hour);". Can someone help me out? Thanks in advance.
for i = 1:size(alight,1)
stn = alight{i,1}; % stn name (string)
hour = alight{i,2}; % hour (number)
pax_alight = alight{i,3}; % count (number)
index = find(board{:,1} == stn & board{:,2} == hour);
if isempty(index)
pax_board = 0;
else
pax_board = board{index,3};
end
net = pax_alight - pax_board;
alight(i,4) = net;
end

답변 (2개)

Akira Agata
Akira Agata 2017년 5월 26일
I would recommend using table to store the data and innerjoin function to find the corresponding passengers. Here is a simple example.
% Test data
alight = table({'Smith';'Johnson';'Williams'},[10;20;30],[40;50;60],...
'VariableNames',{'Name','Hours','Count'});
board = table({'Johnson';'Lucy';'Smith'},[20;50;30],[5;10;15],...
'VariableNames',{'Name','Hours','Count'});
% Find the corresponding data, and store the result to alight.Net column
% (in this case, only Johnson matches.)
[~, ia, ib] = innerjoin(alight, board, 'Keys', [1 2]);
alight.Net = alight.Count;
alight.Net(ia) = alight.Net(ia) - board.Count(ib);

Jan
Jan 2017년 5월 26일
The failing line can be replaced by:
index = find(strcmp(board(:,1).', stn) & [board{:,2}] == hour);

카테고리

Help CenterFile Exchange에서 .NET Enumerations in MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by