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

1 次查看(过去 30 天)
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

采纳的回答

Voss
Voss 2024-5-8
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 个评论
Stephen23
Stephen23 2024-5-9

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

Using caller is correct, as Voss showed.

请先登录,再进行评论。

更多回答(1 个)

Steven Lord
Steven Lord 2024-5-8
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.

类别

Help CenterFile Exchange 中查找有关 Software Development Tools 的更多信息

产品


版本

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by