When using assignin in subfunction A to create a variable in the workspace of subfunction B, the variable is being overwritten by a MATLAB built-in function with the same name

8 visualizaciones (últimos 30 días)
Here is a similar example code. In the original code, there are numerous variables, making it difficult to refactor the code structure or rename variables. I aim to understand the root cause of the error. Specifically, in the example code, even though a variable beta exists in the workspace of subfunction test_beta, MATLAB still recognizes beta as the built-in function. Notably, this issue does not occur when the variable is assigned in the base workspace of the main program.
output = test_beta(10);
Not enough input arguments.

Error in beta (line 19)
y = exp(betaln(z,w));

Error in solution>test_beta (line 6)
output = beta;
function output = test_beta(input)
test_beta2(input)
output = beta;
end
function test_beta2( input )
assignin('caller', 'beta', input);
end

Respuesta aceptada

Matt J
Matt J el 22 de Mzo. de 2025
Editada: Matt J el 22 de Mzo. de 2025
The real solution is this,
function output = test_beta(input)
output = test_beta2(input);
end
function beta=test_beta2( input )
beta=input;
end
but if you must use assignin, you can get around the issue by doing,
output = test_beta(10)
output = 10
function output = test_beta(input)
beta=[];
test_beta2(input)
output = beta;
end
function test_beta2( input )
assignin('caller', 'beta', input);
end

Más respuestas (0)

Categorías

Más información sobre Startup and Shutdown en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by