file open and write issues
1 回表示 (過去 30 日間)
古いコメントを表示
hi, I have k number of directories inside which there are l number of files. Now I want to open all the files one by one and write magic matrix of size l inside it. Now, everything's fine except when I try to write the file it does not work. Elements in the matrix are separated by '-' i.e. 1*3 matrix would simply look like 3-5-8. please help I dont know why I am getting an error on "fprintf(fid1,'%d-',magicmt(m,1:(l-1)))"
clc
clear all
nr_dir=input('Enter no. of directories to be created')
nr_magic=input('Enter the size for magic matrix')
%loop to create directory
for i=1:nr_dir
my_dir=strcat('dir',num2str(i))
m=(mkdir(my_dir)) %loop to create file
for j=1:nr_magic
file_str=strcat('file',num2str(j),'.txt')
full_file_str=strcat('dir',num2str(i),'\',file_str)
fid=fopen(full_file_str,'wt')
fclose(fid)
j=j+1
end
i=i+1
end
%%write to files
for k=1:nr_dir
for l=1:nr_magic
fid1=fopen(strcat('dir',k,'\','file',l,'.txt'))
magicmt=magic(l)
for m=1:size(magicmt,2) %through columns
fprintf(fid1,'%d-',magicmt(m,1:(l-1))); %place *** upto n-1th column only
fprintf(fid1,'%d',magicmt(m,l)) %nth column
fprintf(fid1,'\n'); %print new line
fclose(fid1)
end
l=l+1
end
k=k+1
end
0 件のコメント
採用された回答
Image Analyst
2017 年 9 月 12 日
Well you have a dash in there so of course it puts it in.
Replace
fprintf(fid1,'%d-',magicmt(m,1:(l-1)));
with
fprintf(fid1,'%d ',magicmt(m,1:(l-1)));
There is no dash after the %d, just a space, so your numbers will be separated by a space instead of a dash.
2 件のコメント
Image Analyst
2017 年 9 月 12 日
It's doing exactly what you tell it to do. I didn't get any error thrown when I ran your code, but I improved it some, and replaced the * with a dash.
% This script creates a magic() matrix and saves into a file
% A magic matrix is where each elements in a row are separated by three asterisks
n=input('Enter the magic number : ')
magicSquare = magic(n)
baseFileName = sprintf('Magic Square %d.txt', n);
fullFileName = fullfile(pwd, baseFileName);
fprintf('Opening %s.\n', fullFileName);
fid = fopen(fullFileName, 'wt')
for ii=1:size(magicSquare,2) %through columns
fprintf(fid,'%d-',magicSquare(ii,1:(n-1))); %place *** upto n-1th column only
fprintf(fid,'%d',magicSquare(ii,n)); %nth column
fprintf(fid,'\n'); %print new line
end
fclose(fid);
fprintf('Done writing out %s.\n', fullFileName);
% Type out the file.
type(fullFileName); % Print to command window.
winopen(fullFileName); % Windows only!
% delete(fullFileName);
Since it seems to be doing what you want, I don't know how to make it do something else unless you give an example of exactly what you want and describe how what it makes now is not like what you want.
その他の回答 (0 件)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!