Reputation: 3854
I have a file and a given matrix size K by N. I want to read that file and save into that array. In which K is determined from size of file divides for N. If that division is not integer, I will add zeros padding at the end of last packet. As the figure, the zeros padding is denoted by yellow color. Finally, I can store the information of file into a array K by N. Could you help me implement that problem by matlab code. Thank you in advance
Update: I would like to share my code. Please look at my code and let me know if it have any problem
file='Lenna.bmp';
N=3;
fid=fopen(file,'r');
inter_list=fread(fid,'*uint8'); %
fclose(fid);
%% Add padding
[m n]=size(inter_list);
numpadding=N-rem(m*n,N);
inter_list(end+numpadding,:)=0;
packet = reshape( inter_list.', [],N);
[K N]=size(packet);
I found a problem that is my inter_list is constructed as following
66
77
54
0
12
0
0
0
0
0
54
0
0
0
40
If I set N=3 that mean the first packet is [66 77 54], second packet is [0 12 0] and so on. However, when I use that code
packet = reshape( inter_list.', [],N); % N=3
Then output is,
66 -58 109
77 102 -60
54 82 99
How to achieve my expected result that is
66 77 54
0 12 0
You can download the file at here
Upvotes: 0
Views: 340
Reputation: 11812
Matlab is a "column major" language (unlike many other). It means the elements of an array will be read/accessed/stored column wise in memory.
Quick example: The array:
A = [ 1 2 3
4 5 6 ] ;
Will be written in memory sequentially (there is no other way) by reading from top to bottom, then left to right (as opposed as "from left to right, then top to bottom"). So in memory, it look like:
A = [ 1 4 2 5 3 6 ] ;
This is also how these values would be indexed if you choose the sequential indexing instead of the 2D matrix indexing.
ex: A(1,3)=3
is the same as A(5)=3
.
The reshape
function, like most Matlab function, will use this ordering as default.
(Matlab doc used to be much more explicit about this but in the recent documentation I could only find a small reference to that at the bottom of one of the example: "The elements in B also maintain their columnwise order from A.")
So in your case, you want your packets to contain N
sequential values, you have to specify that to the reshape
function as the first parameter:
packet = reshape( inter_list , N , [] ) ;
Now that will give you a [N K]
matrix instead of a [K N]
, this is where the transpose operation will achieve what you want. It has to be applied on the result of the reshape, not in the input. So your full instruction should be:
packet = reshape( inter_list , N , [] ).' ; %'// the transpose ".'" operation is applied on the result of the reshape operation
The rest of your code is ok.
Upvotes: 1