Publish function inside a package

2 次查看(过去 30 天)
Davide Zilio
Davide Zilio 2019-11-20
回答: Ishu 2024-2-7
Hi
I am trying to publish the content of a function from an another function inside the same file.
See example below
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function funTestA(a,b)
options = struct('format','html','outputDir','C:\');
options.codeToEvaluate = sprintf('funTestB(%d,%d)',a, b);
funTestB(a,b)
publish('funTestB',options)
end
function funTestB(a,b)
disp(a+b)
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Note that the both funcitons are inside funTestA.m
When I tried to run it I have the following error message.
>> funTestA(3,5)
8
Error using publish
Cannot find "funTestB".
Any help in using publish in this context is appreciated.

回答(1 个)

Ishu
Ishu 2024-2-7
Hi Davide,
You are getting this error because "publish" function is used to publish the documentaion of files so as an argument you have to provide a file name. When you use "publish('funTestB',options)" then the MATLAB's publish function is looking for a separate file named "funTestB.m" to publish, but funTestB is defined as a local function within funTestA.m. The publish function expects the function to be in its own file.
You can create a temporary file within "funTestA.m" which will be containing the defination of "funTestB" function, and then run "publish" with that file name.
function funTestA(a, b)
% Define options for publishing
options = struct('format', 'html', 'outputDir', 'html');
% Create a new file that calls funTestB with the desired arguments
tempFileName = 'tempScriptToPublish.m';
tempFileContent = sprintf('result = funTestB(%d,%d);', a, b);
% Write the content to the temporary file
fid = fopen(tempFileName, 'w');
fprintf(fid, '%s', tempFileContent);
fprintf(fid, '\nfunction result = funTestB(a, b)\n');
fprintf(fid, 'result = a + b;\n');
fprintf(fid, 'disp(a + b);\n');
fprintf(fid, 'end\n');
fprintf(fid, '\n');
fclose(fid);
% Publish the temporary file
publish(tempFileName, options);
% Clean up: Delete the temporary file after publishing
delete(tempFileName);
end
For more information you can refer to the below documentation:
Hope it helps!

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

产品


版本

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by