How to populate a cell array with vector elements?
Mostrar comentarios más antiguos
I have a cell array consisting of n-number of cells, each of different size. I also have a vector consisting of n-number of elements. I'd like to populate the cells with the corresponding elements from the vector.
1 comentario
Is this a homework question? If it is: Sorry for posting the easy solution. Note that providing it as your solution would be a kind of cheating. If you ask a homework question, clarify this detail such that the answer can be formulated as hints and you have the chance to solve it by your own.
Respuesta aceptada
Más respuestas (2)
Jan
el 4 de Jul. de 2017
I have a cell array consisting of n-number of cells
I assume this means:
n = 17;
C = cell(1, n);
But what does this mean:
each of different size.
? A short explanation would avoid to let the readers guess.
I also have a vector consisting of n-number of elements.
Perhaps this is:
x = rand(1, n)
and
I'd like to populate the cells with the corresponding elements from the vector.
might mean:
for k = 1:numel(C)
C{k} = x(k);
end
Or easier:
C = num2cell(x);
Does this help? If not explain what "each of different size" means.
1 comentario
Yerzhigit Bapin
el 4 de Jul. de 2017
Guillaume
el 4 de Jul. de 2017
Assuming you want to append the elements of your vector to vectors in the corresponding cells of your cell array:
result = arrayfun(@(c, el) [c{1}, el], yourcellarray, yourvector, 'UniformOutput', false);
The above assumes that the vectors in the cell arrays are row vectors. If they are column vectors, then it's [c{1}; el]
6 comentarios
Yerzhigit Bapin
el 4 de Jul. de 2017
Jan
el 4 de Jul. de 2017
A nx1 matrix is a vector.
I didn't get the desired result It's very unclear what is your desired result (and for that matter, the starting point). Provide an example of inputs and desired output.
The statement added an additional element from the vector to each cell. Yes, exactly as described in my sentence: "Assuming you want ...".
As Jan says, a nx1 matrix is a vector, a column vector to be precise. The definition of a vector is a matrix whose all dimensions but one have size 1.
Yerzhigit Bapin
el 4 de Jul. de 2017
Jan
el 4 de Jul. de 2017
@Yerzhigit Bapin: Do you see that an answer is much easier now after you have explained the wanted procedure clearly?
Guillaume
el 4 de Jul. de 2017
OH, that certainly wasn't clear from the initial question.
A one-liner solution:
result = arrayfun(@(c, el) repmat(el, size(c{1})), yourcellarray, yourvector, 'UniformOutput', false);
Categorías
Más información sobre Data Type Identification en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!