Printing repeating double header with dlmwrite and for loop

8 次查看(过去 30 天)
I'm trying to print a '.dat' file with the code below that produces a repeating double header 776 times. The value at the end of each header line should change by +1.
for ii = 103:878
dlmname3 = 'Input_commands.dat';
header={'*Elset, elset=CALIBRATED_210_FINAL_VOLUME' num2str(ii)};
for ik = 1:776
header2={'*Include, input=Final_element_' num2str(ik) '.dat'};
end
dlmwrite(dlmname3, header,'delimiter','','-append');
dlmwrite(dlmname3, header2,'delimiter','','-append');
fclose all;
end
I would like this code to produce:
*Elset, elset=CALIBRATED_210_FINAL_VOLUME103
*Include, input=Final_element_1.dat
*Elset, elset=CALIBRATED_210_FINAL_VOLUME104
*Include, input=Final_element_2.dat
*Elset, elset=CALIBRATED_210_FINAL_VOLUME105
*Include, input=Final_element_3.dat
and so on up volume 878 and final_element_776...
However it is currently producing:
*Elset, elset=CALIBRATED_210_FINAL_VOLUME103
*Include, input=Final_element_776.dat
*Elset, elset=CALIBRATED_210_FINAL_VOLUME104
*Include, input=Final_element_776.dat
*Elset, elset=CALIBRATED_210_FINAL_VOLUME105
*Include, input=Final_element_776.dat
etc...
I've tried a few variations but it's never quite right. I think the problem is (ik) finishes before the second iteration of (ii) hence 776 showing up on all even lines. I know I could normally do it with one loop but I need the alternate lines to use and have different values.
I think I am missing something simple for the solution so apologies in advance for that but also a thank you in advance for any help you might be able to provide!

采纳的回答

Jan
Jan 2016-12-6
编辑:Jan 2016-12-6
dlmwrite is not useful here. Faster:
dlmname3 = 'Input_commands.dat';
fid = fopen(dlmname, 'W'); % Upper-case W
if fid == -1
error('Cannot open file: %s', dlmname3); % Never open without a check
end
for ii = 103:878
fprintf(fid, '*Elset, elset=CALIBRATED_210_FINAL_VOLUME%d\n', ii);
fprintf(fid, '*Include, input=Final_element_%d.dat\n', ii-102);
end
fclose(fid);

更多回答(1 个)

DC
DC 2016-12-6
I've since solved this having come back to it after a little break - think I'd been staring at the screen for too long. It was a VERY simple fix as suspected. Nothing at all ground breaking but will post it on the off chance it might help someone, somewhere, someday.
for ii = 103:878
dlmname3 = 'Input_commands.dat';
header={'*Elset, elset=CALIBRATED_210_FINAL_VOLUME' num2str(ii)};
header2={'*Include, input=Final_element_' num2str(ii-102) '.dat'};
dlmwrite(dlmname3, header,'delimiter','','-append');
dlmwrite(dlmname3, header2,'delimiter','','-append');
end

类别

Help CenterFile Exchange 中查找有关 Get Started with MuPAD 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by