MATLAB: Error using fwrite Invalid file identifier. Use fopen to generate a valid file identifier- eventhough fid is positive

fwrite error even though fid id positive

Hello all, I am trying to edit a base txt file by trying to locate a particular string and then replacin gthe text inder that heading (match1 match2 etc). Even though my file identifier is positive fwrite command is creating a problem. I am not quite sure as to how to proceed from here. Please find below my code and feel free to give suggestions.
cd ('filelocation')
format long g
z=1;
current=dlmread('current.txt')
[Length Width]=size(current)
% open file for reading
fidr= fopen('Base.yml','r');
for k = 1:Width-1
% open file for writing
filename=['Base_',num2str(k),'.yml'];
fidw= fopen(filename,'w')
for i = 1:Length
fidw= fopen(filename,'w')
% RUN until the end of file
while(~feof(fidr))
% get file identifier for next line
str=fgets(fidr);
% match the string in the bracket


match = regexp(str,'- Name: Current1','match');
% match the string in the bracket
match1= regexp(str,'CurrentDepth, CurrentFactor, CurrentRotation:', ...
'match');
% match the string in the bracket
match2= regexp(str,'ActiveCurrent: Current1','match');
if(~isempty(match))
str=[' ' '- Name: Current2',char(10) ];
elseif(~isempty(match2))
str=[' ' 'ActiveCurrent: Current2',char(10) ];
end
% this is where my error gets thrown up
fwrite(fidw,str);
if(~isempty(match1))
for i=1:Length
fprintf(fidw,'%s%1.0f%s%1.5f%s%1.0f%s\n', ...
' - [',current(i,1),', ',current(i,k+1),', ',0,']');
end
fgets(fidr)
fgets(fidr)
fclose(fidw);
end
end
end
end

Best Answer

...
filename=['Base_',num2str(k),'.yml'];
fidw= fopen(filename,'w')
for i = 1:Length
fidw= fopen(filename,'w')
...
The file is already open...and you've overwritten the file handle with the subsequent call so you've orphaned the original one.
Not sure what your intent is, but superficially looks as though you simply need to remove the fopen and the fclose inside the loop. Since you don't ever change filename that'll write everything to one file; otherwise you would need to keep them inside the loop but remove the open outside and also do something to create another filename each pass.