Pass parameter from batch file to .m Matlab program

조회 수: 3 (최근 30일)
Tik Ho HUI
Tik Ho HUI 2024년 10월 3일
답변: Tik Ho HUI 2024년 10월 4일
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 ?

답변 (2개)

Jaimin
Jaimin 2024년 10월 3일
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 2024년 10월 4일
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

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by