Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
empty argument - test(1, , 2)

Subject: empty argument - test(1, , 2)

From: Occa O'Connor

Date: 7 Feb, 2009 05:44:01

Message: 1 of 5

I'm trying to create a function which has all the inputs are optional but want the ability for the user to skip past an input variable by putting in two commas. The reason I want this is I'm trying to make functions which provide answers to distributinos but dependant on which variable they leave blank will be the variable the function will solve for.

Simple eg.

function ans = test(x, y, z)
% ans = test(x, y, z) will solve equation x/y - z*y = 0
% equation will be solved for which ever variable is left off input arguments
if isempty(x), ans = z*y^2, end
if isempty(y), ans = sqrt(x/z), end
if isempty(z), ans = x/y^2, end
end

I've looked at using varargin and inputParser but don't think I can get arround the error returned by "Error: Expression or statement is incorrect--possibly unbalanced (, {, or [."

I can't catch the error because it doesn't happen inside the function.

Any ideas?

Thanks

Occa

Subject: empty argument - test(1, , 2)

From: Phil Goddard

Date: 7 Feb, 2009 06:13:02

Message: 2 of 5


The placeholder in MATLAB is an empty matrix, created with an opening then closing square bracket, so you need

test(1,[],3)
test([],[],3)
test([],2,3)

Phil

Subject: empty argument - test(1, , 2)

From: Occa O'Connor

Date: 7 Feb, 2009 06:43:01

Message: 3 of 5

Thanks for the help Phil. Not qiute as clean as I wanted but it looks like only way.
Cheers
Occa

Subject: empty argument - test(1, , 2)

From: Matt Fig

Date: 7 Feb, 2009 07:19:01

Message: 4 of 5

I tend to think this is much cleaner:


function anss = test(x1, x2, vartosolve)
% test(x, y, z) will solve equation x/y - z*y = 0
% Pass in the two variables you have, in alphabetical order, and the
% variable you wish to solve for.
%
% Examples:
%
% test(1,3,'y') % Solves 1/y - 3*y = 0 for y.
% test(2,4,'x') % Solves x/2 - 4*2 = 0 for x.
% test(1,5,'z') % Solves 1/5 - z*5 = 0 for z.

switch vartosolve
    case 'x'
        anss = x2.*x1.^2,
    case 'y'
        anss = sqrt(x1./x2)
    case 'z'
        ans = x1./x2.^2
    otherwise
       error('Variable to solve for is missing or incorrect. See help.')
end











F>HhO<ZGZZJ=ZZBJJK<JO(@D@CJPCZJaZ>@<D=@O<GT<H<IZ4Pa zIK<QtC

Subject: empty argument - test(1, , 2)

From: Occa O'Connor

Date: 7 Feb, 2009 16:50:03

Message: 5 of 5

Thanks Matt, both you and Phil have helped alot of people on this Forum, a big thanks from me.

Cheers

Occa

Tags for this Thread

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us