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?
Show older comments
The file has number of elements want to use only first 1000 elements???? Help me... Thanx in advance..
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
dpb
on 5 Oct 2013
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...
Deepika
on 5 Oct 2013
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...
Image Analyst
on 5 Oct 2013
Please attach your mat file. You'll have to zip it first (I think) and then use the paper clip icon.
Deepika
on 5 Oct 2013
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!