Borrar filtros
Borrar filtros

Save and Load a matrix

61 visualizaciones (últimos 30 días)
Kamuran
Kamuran el 19 de Dic. de 2015
Comentada: Stephen23 el 7 de Nov. de 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 comentarios
Nicle Davidson
Nicle Davidson el 25 de Sept. de 2021
Editada: Nicle Davidson el 25 de Sept. de 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 el 7 de Nov. de 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.

Iniciar sesión para comentar.

Respuestas (1)

DGM
DGM el 7 de Nov. de 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.

Categorías

Más información sobre Matrices and Arrays en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by