2

i want to clarify how to control returning of variables from function in matlab,for exmaple let us consider this code

function [x y z]=percentage(a)
 n=length(a);
  maximum=0;
  minimum=0;
   subst=0;
 minus=0;
 plus=0;
 minus_perc=0;
 plus_perc=0;
  for i=1:1:n
      if a(i)>0
          plus=plus+1;
      else
          minus=minus+1;
      end
end
      minuc_perc=minus/n;
      plus_perc=plus/n;
                 maximum=max(minus_perc,plus_perc);
                  minimum=min(minus_perc,plus_perc);
                  subst=maximum-minimum;
                  x=plus_perc;
                  y=minus_perc;
                  z=subst*100;
                  if plus_perc>minus_perc 
                      disp('among the successful people,relevant propession was choosen by');
                      disp(z)
                      disp('% people');
                  else
                         disp('among the successful people,irrelevant propession was choosen by');
                         disp(z);
                         disp('% people');
                  end

     end

what i want to return is plus_proc,min_proc and subst,but when i run following command,get result like this

[c d e]=percentage(a)
among the successful people,relevant propession was choosen by
   58.3333

% people

c =

    0.5833


d =

     0


e =

   58.3333

so i think something is wrong,array is like this

a =

     1    -1     1     1    -1     1    -1    -1     1     1     1    -1

so ones again,i want to return plus_proc,minus_proc,and subst

1
  • i found my mistake,instead of minus_proc,there was minuc_proc,sorry ones again.if you like answer and i will upvote and accept Commented May 1, 2013 at 14:09

1 Answer 1

5

To return a variable in matlab you just assign into one of the specified return parameters. For example: to return the number five I would use:

function [foo] = gimmeFive()
    foo = 5;
end

Your code is not giving you the right answer because you have a typo:

minuc_perc=minus/n;

should be

minus_perc=minus/n;

You could greatly simplify the function by taking advantage of the find function, like so: Find the indeces of any element of a > 0, count them.

plus = length(find(a > 0)); 
plus_perc = plus ./ length(a);

Or if you want to cut even more out: a > 0 gives us a vector of 0 and 1, so sum up the 1's

plus = sum(a > 0);
plus_perc = plus ./ length(a);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.