Using function in a serial code
1 view (last 30 days)
I have a function shown below:
function [ncell,phis,vac,nccel,ccell] = micro_poly_cell(Nx,Ny,ncell,R)
ncell == 2;
nccel = 0;
R2 = R*R;
icell = icell+1;
dx = xc(icol,irow);
dy = yc(icol,irow);
if((i- dx)*(i-dx) + (j-dy)*(j-dy) < R2)
vac(1) = 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?
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.