Pass variable name through variable of a custome save function made error
조회 수: 8 (최근 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
댓글 수: 0
채택된 답변
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
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
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!