Reputation: 1072
I need to save multiple arrays to a text file in the following format:
n=2 %number of arrays
r=3 %number of rows in the first array
1 2 3 % actual data
4 5 6
7 8 9
r=3 %number of rows in the second array
5 6 7 % actual data
1 2 3
7 8 9
Would you help please
Upvotes: 1
Views: 8128
Reputation: 1123
What have you done so far?
As a general rule, for this sort of thing your friends are the functions fprintf, which prints data to a file, and varargin, which allows you to supply a variable-length argument list to a function. A good signature for a function that handles this sort of task might therefore be
function [output_args] = pretty_save_to_file(fName, varargin)
Here fName
is the name of the file you'd like your data saved to and varargin
is a placeholder for the names of the matrices you'd like to save. Once you've filled in the gory details of the function, you should be able to call it using something like
pretty_save_to_file('output.txt', A, B, C) % prints matrices A, B, and C to output.txt
In addition, since you're looking to determine the number of rows in each matrix, you'll probably find the following snippet involving the size function useful:
[nrows, ncols] = size(A); % Stores the number of rows and columns of A in nrows, ncols
Finally, the fprintf function allows you to specify the desired formatting of your matrix.
Upvotes: 1
Reputation: 4398
Use fprintf. If your arrays are stored in a cell array so that you can iterate through them.
arrays = cell(N, 1); %A cell array of arrays
f = fopen('output.txt', 'w');
fprintf(f, 'n=%i\n', N);
for i=1:N
rows = size(arrays{i}, 1);
fprintf(f, '\nr=%i\n', rows);
for j=1:rows
fprintf(f, '%g ', arrays{i}(N, :));
fprintf(f, '\n');
end
end
fclose(f);
Upvotes: 4