Merge a selected rows to creat a single row

4 次查看(过去 30 天)
I [have] a long (2000x2) (array/matrix) " the data is double "
and i want to Merge each 8 rows to get a (667x6 array)
if the last row is less than 6 , then it's gonna fill the begging of it with zeros .
a small example :
x = 1 2
3 4
5 6
7 8
result = 1 2 3 4 5 6
0 0 0 0 7 8
thank you in advance

采纳的回答

dpb
dpb 2020-2-28
编辑:dpb 2020-2-28
EDITED for ROW ORDER CORRECTION -- dpb
function X=reshapeNperRow(x,Nper)
% X = reshapeNperRow(x,Nper)
% reshapes input array x to have Nper elements per row
% if not evenly divisible number elements total, augment
% last row by prepending zeros
x=x.'; % transpose for column major order internal storage
N=numel(x); % total number elements
Nrep=fix(N/Nper); % how many output full rows in input array
Nused=Nrep*Nper; % how many elements used for even rows
X=reshape(x(1:Nused),Nper,[]).'; % output those in desired shape
Nleft=N-Nused; % are there any left over?
if Nleft, X=[X;[zeros(1,Nper-Nleft) x(Nused+1:end)]];,end % if so add them to end
end
OK, I'll actually test it this time... :)
>> a=reshape(1:15,[],3).' % test input...
a =
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
>> reshapeNperRow(a,6)
ans =
1 2 3 4 5 6
7 8 9 10 11 12
0 0 0 13 14 15
>>
looks as advertised!
Added some comments so can see what's going on each line.
NB: Think about how to build such arrays from builtins rather than having to construct manually. Learning about memory storage patterns is big key for many optimizations in writing ML code!
  2 个评论
salah roud
salah roud 2020-2-28
编辑:dpb 2020-2-28
thank you so much you are a legend
Could you tell me how to edit the code so I can get the desired values ..
because the output is not exactly as I asked :/
For example
>> a = [ 1 2 3 4 5 ; 6 7 8 9 10 ; 11 12 13 14 15]
>> Y = reshapeNperRow(a,6)
I get this result
Y =
1 6 11 2 7 12
3 8 13 4 9 14
0 0 0 5 10 15
But i want it this way
Y =
1 2 3 4 5 6
7 8 9 10 11 12
0 0 0 13 14 15
you got what i mean :/
and thank you so much
dpb
dpb 2020-2-28
Huh. I thought I had done that but see I missed a code line in the final...
You should be able to recognize what went wrong; the orientation array to select the first N elements has to be in column major order, but you want row major. But, if the array is transposed initially, then the row,column counts are wrong in computing things so have to do that first, then transpose...
In fact, the final is somewhat different logic than I started with; the ending version doesn't need [nr,nc] at all...it was in editing that I see I deleted one line off from where I intended in cleaning up the posted version.
Thanks for pointing out the error in my ways! :)

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

产品


版本

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by