필터 지우기
필터 지우기

How can prelocate arrays?

조회 수: 1 (최근 30일)
Ayob
Ayob 2013년 4월 23일
I have an array like A which I want to have all of its elements zero by using Matlab features like zeros(x) function.
for example:
A=[1*3][1*3][1*3][1*3]
Each 1*3 matrix in the array A should have 3 zero.
I know how to make matrices with zero elements e.g zeros(2,3) but I don't know how to use it for array shown above with Matlab features without using simple loops.
  댓글 수: 3
Ayob
Ayob 2013년 4월 23일
편집: Ayob 2013년 4월 23일
>> A{1}=[0 0 0]
A = [1x3 double]
>> A{2}=[0 0 0]
A = [1x3 double] [1x3 double]
>> A{3}=[0 0 0]
A = [1x3 double] [1x3 double] [1x3 double]
Does it look clear now?
Matt J
Matt J 2013년 4월 23일
If A is a cell array, then my Answer below will be applicable.

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

채택된 답변

James Tursa
James Tursa 2013년 4월 23일
This method uses a shared data copy of [0 0 0] to populate the individual cell elements, so it is memory efficient:
A = cell(1, n); % Or whatever size you need
A(:) = {[0 0 0]};
However, pre-allocating cell elements only makes sense in certain cases. E.g., it does not make sense if you are simply going to overwrite the elements with something else downstream in your code. How is the array A going to be used downstream in your code?
  댓글 수: 3
Ayob
Ayob 2013년 4월 23일
It doesn't work in my program: MATLAB error: ??? The following error occurred converting from cell to double:
Error using ==> double
Conversion to double from cell is not possible.
Error in ==> ThesisMLS at 81
A(:)={[0 0 0]};
James Tursa
James Tursa 2013년 4월 24일
Be sure to do A = cell(1, n) first.

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

추가 답변 (1개)

Matt J
Matt J 2013년 4월 23일
편집: Matt J 2013년 4월 23일
This might be what you need
out = cellfun(@(c) zeros(size(c)), A, 'uni',0),
It has shorter syntax than a loop, but is not faster.

카테고리

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