how to load a matfile and access & process its content.

1 view (last 30 days)
I am explaining my doubt with an example.
Eg: suppose i load a matfile named 'validation.mat' using load command, the contents of it get stored under a variable named " validation" in my workspace. so now can retrieve its content using validation(1,1) ,and so on.(manually created matfile)
now i want to programmatically create a similar kind of matfile at particular directory and give it name "execution.mat". and i also want to load this newly created matfile using load command to workspace and perform actions like executiom(1,1) = 2; and so on.
also note that this nameword "execution" i am deriving from a field of structutre.
so psuedocode would go as:
  1. file_name = struct.somefield ------> here filename contains "execution"
  2. now using file_name which contains execution i want to create execution.mat,load execution and process it

Answers (1)

Sindar
Sindar on 15 Jun 2020
% create a structure with field 'somefield' containing the desired filename
mystruct = struct('somefield','execution')
% create some example data
myvar = rand(2,2);
% extract the filename mystruct
filename = mystruct.somefield;
% save a mat file named execution.mat containing myvar
save([filename '.mat'],'myvar')
% load data from execution.mat into the newstruct structure
newstruct = load([filename '.mat']);
% replace the row-1/column-1 data with 2
newstruct.myvar(1,1) = 2;
% overwrite execution.mat with the new value for myvar
% note that since myvar is a field of newstruct, you need the -struct argument to save it correctly
save([filename '.mat'],'-struct','newstruct')
Some notes:
  • struct is an important function, don't overwrite it
  • note that loading data from a matfile into a variable creates a structure with corresponding fields. I think this is generally a better idea than an unassigned load (e.g., load([filename '.mat']); ) which dumps the variables directly into the workspace
  • If you want the names of variables themselves to be determined programmatically, read this and reconsider

Tags

Products


Release

R2013b

Community Treasure Hunt

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

Start Hunting!