Write values of large cell to .inp file
4 views (last 30 days)
Show older comments
I have a 10 by 1 cell titled elsets, in each cell I have a 200x1 double.
I would like to print these values to a .inp file. I have no trouble opening the file but, how do I write the values of the doubles 15 lines and once the row is filled, have MATLAB automatically write numbers to the next line?
I need the final results to look like a .inp file for abaqus.
filename = 'test.inp';
fid = fopen(filename, 'w');
for phase = 1:10
fprintf(fid, '*Elset, elset=Phase1_%d \n', phase);
for i = 1:cell2mat(elsets)
fprintf( '%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n', elsets{i});
end
end
0 Comments
Accepted Answer
Stephen23
on 16 Jun 2023
Do not use nested loops! Your approach mixes up nested loops and a format string that prints each line. Better:
fmt = repmat(',%d',1,16);
fmt = [fmt(2:end),'\n'];
fnm = 'test.inp';
fid = fopen(fnm,'wt');
for phase = 1:numel(elsets)
fprintf(fid, '*Elset, elset=Phase1_%d\n', phase);
fprintf(fmt, elsets{phase});
end
fclose(fid); % !!! ALWAYS remember to FCLOSE any file that you FOPEN !!!
More Answers (1)
Kautuk Raj
on 16 Jun 2023
A combination of fprintf and loops can be used to write the values of the doubles in your cell array to a text file. A sample code that demonstrates one way to do this:
% Open the output file for writing
fid = fopen('output_file.inp', 'w');
% Loop over each cell in the elsets cell array
for i = 1:numel(elsets)
% Get the current double array
current_array = elsets{i};
% Loop over each element in the double array
for j = 1:numel(current_array)
% Write the current value to the output file using fprintf
fprintf(fid, '%f ', current_array(j));
% Check if we have written 15 values on this line
if mod(j, 15) == 0
% If we have, write a newline character to start a new line
fprintf(fid, '\n');
end
end
% After writing all the values for the current array, write a newline
% character to separate the arrays
fprintf(fid, '\n');
end
% Close the output file
fclose(fid);
Each line in the file contains 15 values separated by spaces. Once the line is filled with 15 values, the next 15 values are written on a new line. After all 200 values for a particular cell in the elsets cell array have been written, a blank line is inserted to separate the values for that cell from the next cell. This pattern repeats for all 10 cells in the elsets cell array.
0 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!