Asked by Ayob
on 23 Apr 2013

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.

*No products are associated with this question.*

Answer by James Tursa
on 23 Apr 2013

Accepted answer

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?

Matt J
on 23 Apr 2013

@Ayob:

**This method uses a shared data copy of [0 0 0] to populate the individual cell elements, so it is memory efficient:**

Though bear in mind that if you save A to a .mat file, the data sharing is lost. Also, this method assumes that all A{i} are the same size. If so, it makes little sense to be using a cell array to hold A's data.

Ayob
on 23 Apr 2013

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
on 24 Apr 2013

Be sure to do A = cell(1, n) first.

Related Content

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
## 3 Comments

## Matt J (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/73278-how-can-prelocate-arrays#comment_145099

We can't recognize what kind of array A is. Please execute

and show us the output.

## Ayob (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/73278-how-can-prelocate-arrays#comment_145102

>> 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 (view profile)

Direct link to this comment:http://www.mathworks.com/matlabcentral/answers/73278-how-can-prelocate-arrays#comment_145108

If A is a cell array, then my Answer below will be applicable.