narginchk的输出参数太多,Matlab的输出太多

The program myfile.m reads a txt file that contains a total of 25 names and numbers like

exemple:

John doughlas 15986

Filip duch 357852

and so on.

The program converts them to

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

Original code below:

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.

The result I want is:

y = myfile

y =

15986 Doughlas John

357852 duch Filip

update: Change it like Eitan T said but did't get the result like above.

Got the result:

'John doughlas 15986'

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

解决方案

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

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.

Hope this helps!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值