필터 지우기
필터 지우기

How can I assign values to elements with same index from multiple cells?

조회 수: 11 (최근 30일)
I have a cell array with the same-size matrix in each cell, say,
a = cell(2);
[a{:}]=deal(rand(2));
and I want to change the first element of the matrix in each cell to values 1,2,3 and 4 respectively. Something equivalent to
a{:}(1,1) = 1:4;
would be ideal however this syntax doesn't work. Is there any other way?
  댓글 수: 2
Walter Roberson
Walter Roberson 2016년 1월 7일
I don't think this can be done with this kind of syntax.
Stephen23
Stephen23 2016년 1월 7일
The best solution is to avoid cell arrays and use multi-dimensional numeric arrays. then this task is trivial to achieve. See Guillaume's answer for an example of how to do this.

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2016년 1월 7일
편집: Guillaume 2016년 1월 7일
Matlab is not clever enough to expand inner indexing into outer cells (plus there's no guarantee it would work, some cells may not even have 4 elements). So you have to do it yourself and you don't have a choice but to use a loop:
vals = 1:4;
for idx = 1:numel(a)
a{idx}(1) = vals(idx);
end
However, if all the matrices are the same dimension, you could simply convert your cell array to a matrix, which then lets you use normal indexing. With your example:
alla = cat(3, a{:});
alla(1, 1, :) = 1:4;
%and if you want it back as a cell array
a = reshape(num2cell(alla, [1 2]), size(a))

추가 답변 (2개)

Stalin Samuel
Stalin Samuel 2016년 1월 7일
[r c] = size(a);
val = 0;
for n1 = 1:r
for n2 = 1:c
val = val+1;
a{n1,n2}(1,1) = val;
end
end

Hamid Arbabi
Hamid Arbabi 2016년 1월 7일
Thank you guys for the comments and answers. I think I will go with Guillaume's suggestion of using multidimensional arrays.
Hamid

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by