Matlab function return value

2020-03-24 08:09发布

I have one program that has function and the problem, return value, it has too many output.

Like exempley: y = text the answer comes up

Error in text (line 2)

if nargin == 0 

Output argument "array" (and maybe others) not assigned during call to "
C:\Users\name\Documents\MATLAB\text.m>text".

The program text.m reads a txt file that contains a couple of names and numbers like

exemple:

John doughlas 15986

Filip duch 357852

and so on. The program convert them to 15986 Doughlas John and so on.

function array = text(~) 
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);

Is there anyway to fix the problem without starting over from scratch?

Grateful for all the answers!

2条回答
ら.Afraid
2楼-- · 2020-03-24 08:32

Here is a working example.

The first part is to create a function called 'functionA' in a filename 'functionA.m'. Then put the following code inside:

    function  result = functionA(N,alpha)
    result = 5;
    return
    end

The second part is to create another Matlab file(i.e. upto you to name it) or you can use the Matlab command window even. Then run the following code:

    getresult = functionA(100,10);
    getresult

After running you get the following answer:

    ans = 
          5
查看更多
Explosion°爆炸
3楼-- · 2020-03-24 08:53

You specify the function output argument in the definition, but you don't assign anything to it in the function body.

For example, in

function y = student(j)                                

your output is y. So you have to assign something to y.

Read more about functions in MATLAB.

查看更多
登录 后发表回答