I have a mat-file of 1-by-500001 matrix. I want to create a 1000-by-1000 matrix from it. How to do this?

Answers (1)

Do you want the first 1000 elements or a 1k X 1k array as the title says? They're not commensurate.
Either way; pick the N that you want and then reshape
Say it's a 1K by 1K...
x=load('yourmatfile');
N=1000; % set the size desired for generality
x=reshape(x(1:N*N),N,N); % keep the N^2 first and reshape to square..
ADDENDUM:
x=load('yourmatfile');
N=1000; % set the size desired for generality
N=min(N,sqrt(length(x)); % modify to make fit if length(x)<N^2
x=reshape(x(1:N*N),N,N); % keep the N^2 first and reshape to square..
That'll fix the overrun error as also noted elsewhere but gets the solution into the Answers section...

7 Comments

Sorry... I didn't get you . Please, elaborate the answer..as I am new to MATLAB. I want to form a 1000*1000 matrix to use in my program from the matrix 1*500001 element matrix...
The above does precisely that -- give it a go. Just substitute the file name of your mat-file in the load statement
doc load
doc reshape
Read and work thru the "Getting Started" section of the documentation
doc
The "Getting Started" button at the upper left...
Sorry dpb.. but when I am using the above commands suggested by you MATLAB shows an error. It shows "Index exceeds matrix dimensions".
Well, that means the mat-file likely isn't as big as you think...
But, you've got to show your work in context to have any hope of direct help.
what does
whos x
report after you load the file?
ERRATUM:
My old eyes failed in counting zeros -- NB:
>> 500001/1000
ans =
500.0010
>>
You can't make a 1000x1000 matris from only half as many elements as are needed...so, indeed the error is correct. The largest square matrix you can create from the .mat file array is one that is
>> floor(sqrt(500001))
ans =
707
elements each way which uses
>> ans*ans
ans =
499849
>>
elements out of the overall 500001.
To automate this, change the suggested script just a smidge --
x=load('yourmatfile');
N=floor(sqrt(length(x))); % How long a side can be of square
x=reshape(x(1:N*N),N,N); % and make an array of that size...
Please attach your mat file. You'll have to zip it first (I think) and then use the paper clip icon.
Don't send; attach it here.
But, can resolve the problem w/o the actual file -- see ERRATUM: posted above that accounts for actual length of the file instead of presuming the request was reasonable/possible.

Sign in to comment.

Asked:

on 5 Oct 2013

Edited:

dpb
on 5 Oct 2013

Community Treasure Hunt

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

Start Hunting!