Splitting an array every n rows
5 次查看(过去 30 天)
显示 更早的评论
Hi everyone,
fairly new at matlab and i am having a problem with arrays.
My goal: I have an array(mx3) of data that i want to separate it every N rows so i can save that (sub)array as a separate file.
I am having trouble with how the loop should be setup:
p=1;
n = ceil(length(Accell)/N); % number of samples
y=N;
for i = 1:n
for q = 1:j
M{i,q} = Accell(p:y,q);
end
end
A obvious problem occurs; the variable p and y stay constant so the row won't change. Accell is my Data en N is the number of rows I want to separate.
so ideally M would be:
M{1,:} = Accel(1:80,:)
M{2,:} = Accel(81:160,:)
etc etc
After this loop I extract the rows of M into a array and save it.
for x=1:size_M % Number of samples (rows) in M
i=1;
while exist(['Saved Data\', num2str(classificatie), '\', num2str(i.', 'D%03d'), '.mat'], 'file')==2
i=i+1;
end
inputs = [M{x,1},M{x,2},M{x,3}];
save((['Saved Data\', num2str(classificatie), '\', num2str(i.', 'D%03d'), '.mat']), 'inputs')
% set(handles.debug, 'string','Measurement values have been saved successful')
end
Right now the code saves the first 80 rows of the data (Accell) in n (samples) files. I know it's very convoluted and I am very open to improvements.
Thank you in advance!
-Vincent
2 个评论
KALYAN ACHARJYA
2018-11-26
Can you elaborate your problem with some example?
Input (consider example as representation) and what result you expect?
采纳的回答
Stephen23
2018-11-26
编辑:Stephen23
2018-11-26
"so ideally M would be:"
M{1,:} = Accel(1:80,:)
M{2,:} = Accel(81:160,:)
etc etc
>> N = 80;
>> A = rand(192,3); % fake data, # of rows != multiple of N.
>> S = size(A);
>> R = N*ones(1,ceil(S(1)/N)); % number of rows in each cell.
>> R(end) = 1+mod(S(1)-1,N); % number of rows in last cell.
>> M = mat2cell(A,R,S(2));
And checking:
>> cellfun('size',M,1)
ans =
80
80
32
Or, if you really want to use a loop, you can use end inside the array indexing:
R = ceil(S(1)/N);
M = cell(R,1);
for k = 1:R
B = (k-1)*N+1;
E = k*N;
M{k} = A(B:min(end,E),:);
end
And checking:
>> cellfun('size',M,1)
ans =
80
80
32
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!