Save and Load a matrix

91 次查看(过去 30 天)
Kamuran
Kamuran 2015-12-19
评论: Stephen23 2021-11-7
Hello, I know this a general question but I am having trouble with saving a matrix and loading it into another code. I do;
save('vzpre1','vz'); % The variable is vz and I save as vzpre1. I just want to save only vz matrix nothing else
vz=load('vzpre1'); % I want to load vzpre1 as vz.
But once I load it. It loads as struc not a matrix.
Any idea?
Thanks
  2 个评论
Nicle Davidson
Nicle Davidson 2021-9-25
编辑:Nicle Davidson 2021-9-25
Try this:
save('vzpre1','vz');
load('vzpre1','vz');
%also use vzpre1.mat instead of just vzpre1, so this code instead:
save('vzpre1.mat','vz');
load('vzpre1.mat','vz');
%so you use a .mat file for this transaction
Stephen23
Stephen23 2021-11-7
Do NOT just LOAD directly into the workspace. That approach is fine when experimenting at the command window, but not for code that you write in scripts or functions (i.e. when you want reliable, repeatable code).
It is much more robust to LOAD into that structure and then access its fields. That is what experienced MATLAB users do.

请先登录,再进行评论。

回答(1 个)

DGM
DGM 2021-11-7
I don't know why nobody has thrown an answer here, but here goes.
The output argument of load() is a struct. You either use the struct contents as they are, or you can assign them to new variables if it makes using them easier.
vz = rand(100); % a matrix
save('vzpre1','vz'); % write the variable to vzpre1.mat
S = load('vzpre1'); % read mat file into a struct
vzfromthefile = S.vz; % explicitly define the incoming variables
immse(vz, vzfromthefile) %show that the two arrays are identical
ans = 0
The command syntax for load avoids this step and might seem inviting, but is generally discouraged for good reason.

类别

Help CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by