0

I want to pass string path to matlab function that I defined and have encountered problem. Here is the summary of what I tried:

I am trying to pass a string variable (in this case a path) declared in bash script to pass that variable to my own function. e.g.

var=/usr/local/
matlab -nosplash -nodesktop -nojvm -r "my_function($var)"

I got the error:

-bash: syntax error near unexpected token `('

To solve this, I tried:

var=/usr/local/
matlab -nosplash -nodesktop -nojvm -r "my_function\($var\)"

which is not something I find in standard references I find online. Regardless, the matlab runs, but I get the error:

Error: The input character is not valid in MATLAB statements or expressions.

To see if the variable is correctly converted, I tried echo:

var=/usr/local/
echo matlab -nosplash -nodesktop -nojvm -r "my_function\($var\)"

and realized that the output is:

matlab -nosplash -nodesktop -nojvm -r "my_function(/usr/local/)"

Since the variable is not string, the error made sense and I tried:

var=/usr/local/
var=$(printf "'%s'" $var)
echo matlab -nosplash -nodesktop -nojvm -r "my_function\($var\)"

which shows:

matlab -nosplash -nodesktop -nojvm -r "my_function('/usr/local/')"

So, I run the above code, but I still encounter the error:

Error: The input character is not valid in MATLAB statements or expressions.

To check if the function exists in path, I tried both pwd and exist() for file. e.g.

matlab -nodesktop -nosplash -nojvm -r "exist('my_function.m')"

The strange thing in this case is that I did not need \(\) and that returned 2, meaning file exists in current path.

I am running out of ideas to try. So let me know how to solve this.

1
  • this is a a bash question not a matlab question Commented Apr 16, 2017 at 22:29

2 Answers 2

1

So I created a function (myfunc) that takes path as an argument and prints list of files in that folder (ls).

$v='~/Documents'
$v2="myfunc('$v')"
$echo $v2
myfunc('~/Documents')
$matlab -nodisplay -nosplash -r $v2

It works. Could you please try this and share your output?

Sign up to request clarification or add additional context in comments.

Comments

1

I can't reproduce your problem; I do not get the first bash error that you describe. Definitely one problem is missing ' ' around $var.

This works for me (granted that my_function is within the matlab path)

var=/usr/local/
matlab -nosplash -nodesktop -nojvm -r "my_function('$var')"

Alternatively try this without -r and like this instead:

#!/bin/bash
var=/usr/local/
path_to_my_function=/some/path  

matlab -nosplash -nodesktop -nojvm << EOF
    addpath('${path_to_my_function}')
    my_function('${var}')
EOF

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.