Write values of large cell to .inp file
4 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Stephen23
2023-6-16
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 !!!
更多回答(1 个)
Kautuk Raj
2023-6-16
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 个评论
另请参阅
类别
在 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!