MATLAB Answers

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

5 views (last 30 days)
Tom
Tom on 19 Sep 2020
Answered: KSSV on 19 Sep 2020
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!

  0 Comments

Sign in to comment.

Accepted Answer

KSSV
KSSV on 19 Sep 2020
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 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by