how can I manipulate the elements of an array of cells based on index? for a double array, I can just do this:
>> j = zeros(4);
>> j(1:8) = 1;
>> j(9:16) = 8;
>> j
j =
1 1 8 8
1 1 8 8
1 1 8 8
1 1 8 8
However, for a cell array, I cannot
>> j = cell(4,1)
j =
[]
[]
[]
[]
>> j{1:4} = [2 3 4]
The right hand side of this assignment has too few values to satisfy
the left hand side.
I could do this with a for loop easily, but I intend to extend this to a cell with ~400 elements.
After this is figured out, I'd also like to be able to do something based on the index, such as:
j = cell(100,1);
j(1:100) = ones(1:100,1);

댓글 수: 1

Stephen23
Stephen23 2015년 7월 1일
편집: Stephen23 2015년 7월 1일
You really need to read the documentation for ones, because providing it with a vector does not make any sense... it does not do what you think it does.
Also you should not use i or j for variable names, as these are both names of the inbuilt imaginary unit.

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

 채택된 답변

Stephen23
Stephen23 2015년 7월 1일
편집: Stephen23 2015년 7월 1일

0 개 추천

"However, for a cell array, I cannot"
Of course you can! Cell array indexing is covered here, and is well worth reading:
But it depends what you expect. What you trying to do here is assign one array to the inside of multiple cells. This does not work. But you can allocate four cells to four cells (these are equivalent):
X(1:4) = {1,2,3,4}
X(1:4) = num2cell([1,2,3,4])
Or one cell (containing an array) to four cells:
X(1:4) = {[2,3,4]}
So if you want a cell array where every cell contains the same element, try this:
X = cell(100,1);
X(:) = {ones(100,1)}

댓글 수: 4

Thank you for the swift answer! The last piece of code is exactly what I am looking for, however it doesn't work.
>> j = cell(4,1)
j =
[]
[]
[]
[]
>> j{1:4} = {[2,3,4]}
The right hand side of this assignment has too few values to satisfy the left hand side.
Stephen23
Stephen23 2015년 7월 1일
편집: Stephen23 2015년 7월 1일
Please see my edited answer, I made a mistake with the brackets.
You actually want to use:
j(1:4) = {[2,3,4]} % Index using parenthesis
Noah Chrein
Noah Chrein 2015년 7월 1일
Ah yes, now this works! Thank you!

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

추가 답변 (1개)

Azzi Abdelmalek
Azzi Abdelmalek 2015년 7월 1일
편집: Azzi Abdelmalek 2015년 7월 1일

0 개 추천

jj=cell(100,1)
jj(1:100) = num2cell(ones(100,1))

댓글 수: 3

Noah Chrein
Noah Chrein 2015년 7월 1일
After doing this exactly calling jj{1} returns just 1, not ones(100,1), that is
jj{1} = [1]
whereas I want:
jj{1} = ones(100,1) = [1 1 ... 1]
Azzi Abdelmalek
Azzi Abdelmalek 2015년 7월 1일
편집: Azzi Abdelmalek 2015년 7월 1일
jj=cell(100,1);
out=cellfun(@(x) ones(100,1),jj,'un',0)
Noah Chrein
Noah Chrein 2015년 7월 1일
Thank you! this works.

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

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품

질문:

2015년 7월 1일

댓글:

2015년 7월 1일

Community Treasure Hunt

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

Start Hunting!

Translated by