File Exchange

image thumbnail

load2var

version 1.0.0.0 (530 Bytes) by Michael Robbins
Load a specific variable from a mat file and returns it.

0 Downloads

Updated 18 Nov 2004

No License

LOAD2VAR loads a specific variable
from a mat file and returns it.
If no variable name is provided,
the first variable is chosen.

Made as an example for "loading mat-files!"

USAGE:
>> a=magic(3);
>> b='not me';
>> save('tmp');
>> clear all;
>> c=load2var('tmp','a')

c = 8 1 6
3 5 7
4 9 2

>> c=load2var('tmp','b')

c = not me

>> c=load2var('tmp')

c = 8 1 6
3 5 7
4 9 2

>> c=load2var('tmp','d')

c = []

IT'S NOT FANCY BUT IT WORKS

Cite As

Michael Robbins (2021). load2var (https://www.mathworks.com/matlabcentral/fileexchange/6303-load2var), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (3)

Stephen Cobeldick

Returning the empty array as a default output is not a good idea, as this hides whether the file contained the requested variable or not. Better to let the function throw an error, and let the user decide how they need to handle that case.

The function is not very efficient: it loads the entire MAT file into memory, even though it only returns one variable. It also relies on EVAL, which is unfortunate as that will make the code slow when it is used in a loop, and has other disadvantages:
https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval

It is easy to write simpler code without EVAL, that only loads the required data, returns any number of variables, and permits any of the syntaxes that LOAD supports:

function varargout = load2var(filename,varargin)
varargout = struct2cell(load(filename,varargin{:}));
end

and tested:

>> A = 'hello';
>> B = 'world';
>> C = 1:3;
>> save('test.mat','A','B','C')
>> clear
>> load2var('test.mat','B')
ans = world
>> [Bnew,Anew] = load2var('test.mat','B','A')
Bnew = world
Anew = hello

Urs Schwarz (us)

michael, this option is available in ML's generic load function starting with r14
see: help load
just a note
urs

Urs Schwarz (us)

michael, this is available in ML's generic load function starting with r14
see: help load
just a note
urs

MATLAB Release Compatibility
Created with R14SP1
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!