Pass variable name through variable of a custome save function made error
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Tran Tran
el 8 de Mayo de 2024
Comentada: Stephen23
el 9 de Mayo de 2024
Hello guy
I am making a custom save function. I tried declare the variable name, file name first in the script then pass them to my custom save function. However when do that the save function in my custom function return error.
Error using save
The argument to -STRUCT must be the name of a scalar structure variable.
But if I call save function with the same declared variables like before, it work. Here is my code. The saveModel function is my custom function. I removed it by the comment line. Thank for your help.
folderName = "E:\KLTN\trained_model\gait_regression"
modelName = "knee_toruqe_trainedModel"
fileName = folderName + "\" + modelName + ".mat"
%saveModel(fileName,modelName)
save(fileName,"-struct",modelName)
function saveModel(file,model)
save(file,"-struct",model)
disp("Save model")
disp(model)
disp("as file")
disp(file)
end
0 comentarios
Respuesta aceptada
Voss
el 8 de Mayo de 2024
In saveModel, the variable model is a string variable containing the name of the struct variable you want to save, right?
The problem is that struct variable doesn't exist in the saveModel workspace. It exists in the workspace where saveModel is called from.
One solution is to use evalin("caller",_) to pop the same struct variable into existence in the saveModel workspace:
modelName = "knee_toruqe_trainedModel"
saveModel(fileName,modelName)
function saveModel(file,model)
S = evalin("caller",model);
save(file,"-struct","S")
end
A better solution is just to pass the actual struct to saveModel and have it save based on that:
saveModel(fileName,knee_toruqe_trainedModel)
function saveModel(file,model)
save(file,"-struct","model")
end
3 comentarios
Stephen23
el 9 de Mayo de 2024
“I evalin the variable from "base" instead of "caller" and it still work.”
Using caller is correct, as Voss showed.
Más respuestas (1)
Steven Lord
el 8 de Mayo de 2024
When you call this code, what does this command show?
whos knee_toruqe_trainedModel
If it shows nothing, try with the correct spelling of the word "torque".
whos knee_torque_trainedModel
I want to see if this is a 1-by-1 struct array.
0 comentarios
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!