Clear Filters
Clear Filters

Publish function inside a package

1 view (last 30 days)
Davide Zilio
Davide Zilio on 20 Nov 2019
Answered: Ishu on 7 Feb 2024
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.

Answers (1)

Ishu
Ishu on 7 Feb 2024
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!

Categories

Find more on Programming in Help Center and File Exchange

Products


Release

R2017b

Community Treasure Hunt

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

Start Hunting!