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

1 visualización (últimos 30 días)
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!

Respuesta aceptada

KSSV
KSSV el 19 de Sept. de 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)] ;

Más respuestas (0)

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by