2

我有一个这样的文本文件:

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 

我想在 matlab 中导入这个文本文件,然后我的输出说 f 和 v 的数量,例如对于这个文件,我有 v=10 和 f=16 的数量,我试图写但我不能。我知道这很简单。

这是我的错误代码:

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);
4

1 回答 1

3

基本上发生的事情是您的 vnum 和 fnum 值没有被保存。您需要将它们存储在某种数组中,如下所示。

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);
于 2012-04-13T15:02:58.717 回答