Can I assign elements of one cell array to multiple elements of another cell array without a loop?

1 次查看(过去 30 天)
For example, I have two cell arrays:
myArray = {'One', 1000; 'Two', 2000; 'Three', 3000; 'Four', 4000; 'One', 5000; 'Five', 6000};
anotherArray = [({'One', 'Two', 'Three', 'Four', 'Five'})', ({1, 2, 3, 4, 5})'];
I would like to assign elements of anotherArray(:,2) to myArray, whenever the elements of their first columns match by using strcmp and afterwards indexing.
idx = cellfun(@(x) strcmp(x, anotherArray(:,1)), myArray(:,1), 'UniformOutput', false);
But obviously, the following doesn't work:
Out = [myArray, anotherArray(idx{:,1},2)];
A for loop would work, and I would get the desired output, but I think there has to be another way without a for loop!
Out = cell(numel(idx),3);
for i = 1:numel(idx)
Out(i,1:3) = [myArray(i,:), anotherArray(idx{i,1},2)];
end
Thanks for any suggestions!

采纳的回答

KSSV
KSSV 2020-9-19
myArray = {'One', 1000; 'Two', 2000; 'Three', 3000; 'Four', 4000; 'One', 5000; 'Five', 6000};
anotherArray = [({'One', 'Two', 'Three', 'Four', 'Five'})', ({1, 2, 3, 4, 5})'];
[c,ia] = ismember(myArray(:,1),anotherArray(:,1)) ;
Out = [myArray anotherArray(ia,2)] ;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by