Robert Seifert
Robert Seifert

Reputation: 25232

Different results when Matlab is executed by Windows cmd

I try to figure out how to use Matlab by the Windows cmd-promt and I get stucked because of a mysterious behavior.

For testing I have the following function-file:

function [ x y ] = testmath( u,v )

x = u*v;
y = u/v;

display(x);
display(y);

end

When I execute this in Matlab prompt I get the correct results:

[x y] = testmath(2,2)
>> x = 4
>> y = 1

Now I want to run the function by the cmd:

matlab -sd myCurrentDirectory -r "testmath 2 2" -nodesktop -nosplash

and I get:

x = 2500;
y = 1;

Can you reproduce it? What can be the reason? Did I made a mistake by passing the parameters?

Upvotes: 1

Views: 75

Answers (1)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38042

In the Windows cmd version, you are calling it with two character arguments ('2') because you forgot the parenthesis. The correct version would be:

matlab -sd myCurrentDirectory -r "testmath(2,2)" -nodesktop -nosplash

Reproduce the "odd" result on the MATLAB command prompt:

>> [x, y] = testmath 2 2
x = 
    2500
y = 
    1

>> [x, y] = testmath(2,2)
x = 
    4
y = 
    1

The outcome is 2500, because the ASCII code for the character '2' is 50. MATLAB uses this number when applying the multiplication operator to one or two characters.

This is called function/command duality; arguments passed without parenthesis are interpreted as strings. Same as

>> disp hello
hello

>> disp('hello')
hello

or

>> load myFile.dat 
>> load('myFile.dat')

it can be convenient, and confusing (as you just noticed :)

Upvotes: 5

Related Questions