2

I have 5 matrices of different dimensions (n = 256, 512, 1024, 2048, and 4096) and I was wondering how I could store them in an array (which I could iterate through in a for loop later). I tried just doing {\tt matArray = [A B C D E];} but it said that horzcat needed dimensions that agreed. I also tried using cells but I might not be using them correctly because I'm getting an error that says, 'Conversion to cell from double is not possible'. Here is the piece of code that's giving me an error:

A=randi(9, 256);
B=randi(9, 512);
C=randi(9, 1024);
D=randi(9, 2048);
E=randi(9, 4096);
matArray=cell(1,5);
matArray(1)=A;
matArray(2)=B;
matArray(3)=C;
matArray(4)=D;
matArray(5)=E;

Do you guys have any idea what's going on? Thanks in advance.

4
  • 1
    Cell arrays are indexed with {}. Or use matArray = [A;B;C;D;E]; Commented Feb 17, 2013 at 0:08
  • George is correct if you don't mind them all ending up in the same array (the ; causes vertical concatenation -and since the first dimension is the same, that will work). Commented Feb 17, 2013 at 0:11
  • I tried matArray[A;B;C;D;E]; before and I got the error: 'CAT argument dimensions are not consistent'. Commented Feb 17, 2013 at 0:11
  • The dimensions are different. The 9 in randi(9, n) refers to the maximum value of an entry in the matrix. So randi(9, 100) would return a 100 x 100 matrix with random entries between 1 and 9. Commented Feb 17, 2013 at 0:12

2 Answers 2

5

Use matArray{1}=A;

That is how you address a cell element. You can reference it later with matArray{1} etc.

You could initialize matArray with all the matrices with a simple statement:

matArray = {A; B; C; D; E};

Note the use of curly braces for cell initialization.

Sign up to request clarification or add additional context in comments.

4 Comments

So if I was referencing matArray in a loop would I say something like: matArray{index}?
If you initialized matArray per this suggestion, matArray{1} would return A, etc.
Okay, sorry but I have one more question. What's the correct way to declare a cell? Is it like I did it above as matArray=cell(1, 5) to give it enough space for the 5 matrices? Thank you very much for your help Floris et al.
Ah, nevermind I see that you've edited your response. Thank you again, you're great!!
-1

You need semicolons to do vertical concatenation.

matArray = [A; B; C; D; E];

2 Comments

That won't work because the matrices are of different dimensions.
but cellArray = { A; B; C; D; E; } will be fine

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.