Using function in a serial code

1 view (last 30 days)
Robert101 on 25 Apr 2022
Commented: Rik on 25 Apr 2022
I have a function shown below:
function [ncell,phis,vac,nccel,ccell] = micro_poly_cell(Nx,Ny,ncell,R)
format long;
phis =zeros(Nx,Ny,ncell);
ncell == 2;
nccel = 0;
R2 = R*R;
icell =0;
for icol=1:ncol
for irow=1:nrow
icell = icell+1;
dx = xc(icol,irow);
dy = yc(icol,irow);
for i=1:Nx
for j=1:Ny
if((i- dx)*(i-dx) + (j-dy)*(j-dy) < R2)
phis(i,j,icell) =0.999;
vac(1) = 0.5;
vac(2) =-0.5;
It is called in a program as
[ncell,phis,vac,nccel,ccell] = micro_poly_cell(Nx,Ny,ncell,R);
I have written a new program. I have removed the first and last line of this function and have put the rest of the code in it. The problem is that the output is not the same as with the first program where function is called in a program. So how to correct it?

Accepted Answer

Rik on 25 Apr 2022
If you insert the body of this function in a different function, you essentially convert this into a script.
The downside of a script is that it shares the workspace with the caller, which means the code can no longer assume a clean workspace. If the code isn't written carefully, that means it can be affected by the code in the caller.
So the answer is: don't. Leave this a function and call it as a function. That way you have encapsulated behavior that is testable and repeatable. If one day you decide to improve the function, you only need to keep input and output the same and you can be certain everything still works.
The function you poseted contains not a single comment. You should start there. Make sure other people can use your function with only the help text at the top. Include comments in every section of your code that explains what is happening and why. It is also a mystery why this function sets a specific format, without actually printing anything.
Rik on 25 Apr 2022
I suspect the problem is that some variable is used in the preceding code, while the function presumes it doesn't exist.
disp(clean_workspace) % created in empty workspace
0 3
disp(polluted_workspace) % created in used workspace
0.3427 3.0000 0.2919 0.4535 0.6440
function vac=clean_workspace
function vac=polluted_workspace
vac=rand(1,5);%set a value in other code
See? Twice the same code, but the results are different. This could have been prevented by making the assumption explicit:
The best solution is to never work with scripts for real work. Only use it for debugging/writing. A function allows encapsulation. It helps you keep your workspace clean and allows treating parts of the process as a black box.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!