Pass variable name through variable of a custome save function made error

1 Ansicht (letzte 30 Tage)
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

Akzeptierte Antwort

Voss
Voss am 8 Mai 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 Kommentare
Stephen23
Stephen23 am 9 Mai 2024

“I evalin the variable from "base" instead of "caller" and it still work.”

Using caller is correct, as Voss showed.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Steven Lord
Steven Lord am 8 Mai 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.

Kategorien

Mehr zu Software Development Tools finden Sie in Help Center und File Exchange

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by