Reputation: 123
I have a text file like this:
v -0.874157 -0.291386 0.388514
v -0.854358 -0.0854358 -0.512615
v 0.57735 0.57735 -0.57735
v -0.646997 -0.539164 -0.539164
v -0.688247 -0.229416 -0.688247
v 0.105409 0.527046 -0.843274
v -0.442326 0.884652 0.147442
v -0.574696 -0.766261 0.287348
v 0.163846 -0.655386 -0.737309
v 0.536656 0.715542 0.447214
f 4 1 2
f 4 2 5
f 9 4 5
f 1 4 8
f 4 9 8
f 10 1 8
f 9 10 8
f 10 9 3
f 3 9 6
f 5 2 6
f 9 5 6
f 1 10 7
f 2 1 7
f 3 6 7
f 10 3 7
f 6 2 7
I wanted to import this text file in matlab and then my output say the number of f and v , for example for this file I have number of v=10 and number of f=16, I tried to write but I couldn't. I know that it is very simple.
here is my wrong code:
function [vnum, fnum]=read(varargin)
filename=varargin{1};
fid=fopen(filename, 'rt');
% this is error message for reading the file
if fid == -1
error('File could not be opened, check name or path.')
end
%
tline = fgetl(fid);
while ischar(tline)
% reads a line of data from file.
vnum = sscanf(tline, 'v %f %f %f');
fnum=sscanf(tline, 'f %d %d %d');
tline = fgetl(fid);
end
vertex=length(strfind(vnum,'v'));
face=length(strfind(fnum,'f'));
fclose(fid);
Upvotes: 2
Views: 11041
Reputation: 39698
Essentially what is happening is your vnum and fnum values aren't being saved off. You need to store them in some kind of an array, as I am showing below.
function [vnum, fnum]=read(varargin)
filename=varargin{1};
fid=fopen(filename, 'rt');
% this is error message for reading the file
if fid == -1
error('File could not be opened, check name or path.')
end
%
tline = fgetl(fid);
MAX_NUM_VALUES=100;
vnum=zeros(MAX_NUM_VALUES,3);
fnum=zeros(MAX_NUM_VALUES,3);
vnum_index=0;
fnum_index=0;
while ischar(tline)
% reads a line of data from file.
if tline[1]=='v'
vnum_index=vnum_index+1;
vnum(vnum_index,:) = sscanf(tline, 'v %f %f %f');
elseif tline[1]=='f'
fnum_index=fnum_index+1;
fnum(fnum_index,:)=sscanf(tline, 'f %d %d %d');
end
tline = fgetl(fid);
end
vnum=vnum(1:vnum_index);
fnum=fnum(1:fnum_index);
fclose(fid);
Upvotes: 3