问题描述
程序myfile.m读取一个txt文件,该文件总共包含25个名称和数字,例如
The program myfile.m reads a txt file that contains a total of 25 names and numbers like
例如:
约翰·唐格拉斯15986
John doughlas 15986
Filip duch 357852
Filip duch 357852
,依此类推.
程序将它们转换为
15986 Doughlas John
357852 duch Filip
这是没有功能的,我得到了太多的输出.
This is without function, with it I get too many outputs.
Error message:
Error using disp
Too many output arguments.
Error in red4 (line 26)
array = disp(All);
以下原始代码:
function array = myfile(~)
if nargin == 0
dirr = '.';
end
answer = dir(dirr);
k=1;
while k <= length(answer)
if answer(k).isdir
answer(k)=[];
else
filename{k}=answer(k).name;
k=k+1;
end
end
chose=menu( 'choose file',filename);
namn = char(filename(chose));
fid = fopen(namn, 'r');
R = textscan(fid,'%s %s %s');
x=-1;
k=0;
while x <= 24
x = k + 1;
All = [R{3}{x},' ',R{1}{x},' ',R{2}{x}];
disp(All)
k = k + 1;
end
fclose(fid);
现在我从诸如功能但我无法通过函数获得如上结果.
Now I have got many good answers from people and sites like functions but I cant get the results like the above with function.
我尝试将它们结合起来并得到一些结果:
I have tried combining them and got some results:
y = 15986 & [a,z,b] = myfile
y = 25 & myfile = x
y = numbers name1,2,3,4 and so one & myfile = fprintf(All)
y = & I used results().namn,
numbers name 1 & results().id, results().lastname
y =
numbers name 2 and so on.
我想要的结果是:
y = myfile
y =
15986 Doughlas John
357852 duch Filip
更新:像Eitan T所说的那样进行更改,但没有得到上面的结果.
update: Change it like Eitan T said but did't get the result like above.
得到结果:
'约翰·唐格拉斯15986'
'John doughlas 15986'
'Filip duch 357852'
'Filip duch 357852'
function C = myfile()
if nargin == 0
dirr = '.';
end
answer = dir(dirr);
k=1;
while k <= length(answer)
if answer(k).isdir
answer(k)=[];
else
filname{k}=answer(k).name;
k=k+1;
end
end
chose=menu( 'choose',filname);
name = char(filname(chose));
fid = fopen(name, 'r');
C = textscan(fid, '%s', 'delimiter', '');
C = regexprep(C{1}, '(\w+) (\w+) (\w+)', '$3 $2 $1');
fclose(fid);
推荐答案
为什么要使用循环?用textscan
一次读取行,并使用regexprep
操纵单词:
Why use loops? Read the lines at once with textscan
and use regexprep
to manipulate the words:
fid = fopen(filename, 'r');
C = textscan(fid, '%s', 'delimiter', '');
C = regexprep(C{1}, '(\w+) (\w+) (\w+)', '$3 $2 $1')
fclose(fid);
结果是一个单元格数组C
,每个单元格都存储一行.对于您的示例,您将获得2×1的单元格数组:
The result is a cell array C
, each cell storing a line. For your example, you'll get a 2×1 cell array:
C =
'15986 doughlas John'
'357852 duch Filip'
我不确定您要怎么做,但是如果您提供更多详细信息,我可以进一步改善答案.
I'm not sure what you want to do with it, but if you provide more details I can improve my answer further.
希望这会有所帮助!
这篇关于Matlab的输出太多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!