MATLAB Answers

ZK
0

Saving variables in the loop.

Asked by ZK
on 28 Jan 2013

Hi Im using fgets to display every line in the file.

fid = fopen('file');

tline = fgets(fid);

while ischar(tline)

    L = (tline);
    tline = fgets(fid);
    disp(tline)    

end

I would like to save every line in the workspace in sequence as L1, L2, L3 ...

Can You propose me a solution?

Thank You.

  0 Comments

Tags

Products

No products are associated with this question.

1 Answer

Answer by Azzi Abdelmalek
on 28 Jan 2013
Edited by Azzi Abdelmalek
on 28 Jan 2013
 Accepted answer

fid = fopen('file');
line1 = fgetl(fid);
res=line1;
while ischar(line1)
 line1 = fgetl(fid);
 res =char(res,line1)
end
fclose(fid);

  5 Comments

ZK
on 28 Jan 2013

Thanks, but yes I know this possibility. most important for me is have to save every line separately in workspace, becouse I work with several files and I dont know how leinght it is, and I can't appeal directly to line becouse it could not exist.

fid = fopen('file');
line1 = fgetl(fid);
res=line1;
k=0
while ischar(line1)
  k=k+1;
  line1 = fgetl(fid);
  assignin('base',sprintf('L%d',k),line1)
end
fclose(fid);
ZK
on 28 Jan 2013

Thank You very much, working great.


Join the 15-year community celebration.

Play games and win prizes!

Learn more
Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!