Pass parameter from batch file to .m Matlab program

2 views (last 30 days)
I have got a batch file which calls up a matlab program as follows :
1.) batch.bat
@echo off
echo Content-type: text/plain
echo.
echo %1
"C:\Program Files\MATLAB\R2024b\bin\matlab.exe"  -nodisplay -nosplash -nodesktop -r "run('C:\xampp\htdocs\IHC\MATLAB_testing.m','%1');exit;"
2.) MATLAB_testing.m
fid = fopen('results.str','w');
fprintf(fid,'%s',param1);
fid = fclose(fid)
==> The batch file will be run with a parameter input, ie . C:> batch.bat 'testing', and I expect the paramter could pass to the MATLAB_testing.m with param1
final aim ==> param1 = "testing" when run with C:> batch.bat "testing".
How could I modify the coding for the purpose ?

Answers (2)

Jaimin
Jaimin on 3 Oct 2024
In the provided code for the "batch.bat" file, the "param1" variable has not been created. To learn how to create it, please refer to the code below.
@echo off
echo Content-type: text/plain
echo.
echo %1
"C:\Program Files\MATLAB\R2024a\bin\matlab.exe" -nosplash -nodesktop -r "param1='%1'; run('<PATH To FILE>'); exit;"
Now, each time the "batch.bat" file is executed, it creates the "param1" variable in the workspace, allowing you to access it using the name "param1".
Kindly refer following code for better understanding.
% MATLAB_testing.m
if exist('param1', 'var') && ~(param1=="")
fid = fopen('results.str', 'w');
fprintf(fid, '%s', param1);
fclose(fid);
else
error('Parameter "param1" not found.');
end
For more information regarding “exist” function kindly refer following MathWorks Documentation:
I hope this will be helpful.

Tik Ho HUI
Tik Ho HUI on 4 Oct 2024
Thank you very much ! It works now !
And may I ask if there is an output variable from .m MATLAB program and wish to return it back to the batch file after running the program. How can the code be modified ??
Example :
1.) batch file batch.bat
@echo off
echo Content-type: text/plain
echo.
echo %1
"C:\Program Files\MATLAB\R2024a\bin\matlab.exe" -nosplash -nodesktop -r "param1='%1'; run('<PATH To FILE>'); exit;"
2.) MATLAB_testing.m
% MATLAB_testing.m
if exist('param1', 'var') && ~(param1=="")
fid = fopen('results.str', 'w');
fprintf(fid, '%s', param1);
fclose(fid);
x = 1;
y = 2;
z = x + y;
else
error('Parameter "param1" not found.');
end
--> Need to return z to batch file

Categories

Find more on Startup and Shutdown in Help Center and File Exchange

Tags

Products


Release

R2024b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!