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

2 ビュー (過去 30 日間)
Tran Tran
Tran Tran 2024 年 5 月 8 日
コメント済み: Stephen23 2024 年 5 月 9 日
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 件のコメント
Voss
Voss 2024 年 5 月 9 日
You're welcome!
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 Center および File ExchangeStructures についてさらに検索

製品


リリース

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by