Write values of large cell to .inp file

조회 수: 4 (최근 30일)
Maggie Chong
Maggie Chong 2023년 6월 15일
댓글: Maggie Chong 2023년 6월 16일
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

채택된 답변

Stephen23
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
Maggie Chong
Maggie Chong 2023년 6월 16일
fmt = repmat(',%d',1,16);
fmt = [fmt(2:end),'\n'];
for phase = 1:size(elset_labels,1)
fprintf(fid, '\n*Elset, elset=Phase1_%d\n', phase);
fprintf(fid, fmt, elsets{phase});
end
Hello Thanks for your code! I noticed there was a small formatting error but overall it works great!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Kautuk Raj
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.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by