Save and Load a matrix

34 Ansichten (letzte 30 Tage)
Kamuran
Kamuran am 19 Dez. 2015
Kommentiert: Stephen23 am 7 Nov. 2021
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 Kommentare
Nicle Davidson
Nicle Davidson am 25 Sep. 2021
Bearbeitet: Nicle Davidson am 25 Sep. 2021
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 am 7 Nov. 2021
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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

DGM
DGM am 7 Nov. 2021
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.

Community Treasure Hunt

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

Start Hunting!

Translated by