Reputation: 3389
I have a large array where the amount of rows will vary, and I would like to split up and export to multiple files.
I was thinking of using the reshape command, but then I realized for this to work the arrays needed to have the same number of rows which will not always be the case.
clear all, clc,clf,tic
num_elm = 11;
num_elm_split = 4; %Splits into columns
t = linspace(1, num_elm, num_elm)';
v = reshape(t, num_elm_split,[]); %Will split array into different columns
%'for' loop to split number of elements
for ii = 1:length(t(:, 1))
ii
end
Example:
If I have an array of 11 values
a = [1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11]
And I want it be split up on every three values and output the data to a file.
ouput1.txt would have in it 1 2 3
ouput2.txt would have in it 4 5 6
ouput3.txt would have in it 7 8 9
ouput4.txt would have in it 10 11
I know I could use the split command in Linux, but I'm trying to use only MATLAB/Octave code.
Upvotes: 0
Views: 858
Reputation: 3389
Here's the code...this may help someone else out
clear all, clc,clf,tic
filesoxplaylistStr='1soxplaylist.pls'; %playlistist filename fix
dirplstmp='/tmp/tmp/';
values = 1 : 11;
binSize = 3;
fileNum = 0;
n = numel(values);
for ii = 1 : binSize : n
part = values(ii : min(n, ii + binSize - 1))';
fileNum = fileNum + 1
%open file to write to
fidsoxpl = fopen(strcat(dirplstmp,filesoxplaylistStr), 'w'); %create and open file to write to for sox playlist join file
for jj=1:length(part)
part_val=part(jj,1) %gets individual filename or values
%create sox file to join
fprintf(fidsoxpl,'File%s=%s%s.wav',num2str(jj),dirplstmp,num2str(part_val,'%06d'));%create playlist data file
fprintf(fidsoxpl,'\n');
end
% close file to write to
fclose(fidsoxpl);
fn=strcat('test',num2str(fileNum,'%02d'));
%join files with sox
syscmd=strcat({'sox '},dirplstmp ,filesoxplaylistStr, {' '},dirplstmp,fn,{'.wav'});
system(syscmd);
%add freq to file name
end
Upvotes: 0
Reputation: 10365
The basic idea is to do it like this:
values = 1 : 11;
binSize = 3;
fileNum = 1;
n = numel(values);
for i = 1 : binSize : n
part = values(i : min(n, i + binSize - 1));
fprintf('File %d contains %s\n', fileNum, mat2str(part));
fileNum = fileNum + 1;
end
Output:
File 1 contains [1 2 3]
File 2 contains [4 5 6]
File 3 contains [7 8 9]
File 4 contains [10 11]
You need to adapt the code in the loop to actually save the data on disk, of course.
Upvotes: 2