Effacer les filtres
Effacer les filtres

Save and Load a matrix

91 vues (au cours des 30 derniers jours)
Kamuran
Kamuran le 19 Déc 2015
Commenté : Stephen23 le 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 commentaires
Nicle Davidson
Nicle Davidson le 25 Sep 2021
Modifié(e) : Nicle Davidson le 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 le 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.

Connectez-vous pour commenter.

Réponses (1)

DGM
DGM le 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.

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by