Finding similar values in two different cell arrays and comparing them?
18 views (last 30 days)
Show older comments
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
0 Comments
Answers (2)
Akira Agata
on 26 May 2017
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);
0 Comments
Jan
on 26 May 2017
The failing line can be replaced by:
index = find(strcmp(board(:,1).', stn) & [board{:,2}] == hour);
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!