Error:Index exceeds matrix dimensions. when Loading .mat file

3 views (last 30 days)
Dear All, I am facing a strange error when loading a .mat file. I have checked that the .mat exists (with exists) and the variable name is not part of problematic ones (i,j length etc.)
The point is, I can load it in the main, but not in the functions which are called by main.
Here is the code:
function [environment] = loadNetworkEnvironment(load,genValue,nodes,environment,plotting)
files=string();
files(1)=string([dynamicPath(),'DistrictHeatingModel\01 Network Data\01 Environmental Data\',load.var1,'.mat']);
files(2)=string([dynamicPath(),'DistrictHeatingModel\01 Network Data\01 Environmental Data\',load.var2,'.mat']);
if true
for i=1:1:length(files)
% Check if file f exists
if exist(char(files(i)),'file')==2
% Derive variable properties
s=whos('-file',char(files(i))); % yes s exists in run through
% Load the file
[file]=load(files{i});% here is the problem, producing the mentioned error
% Check if the file is consistent with the network data
if length(file.([s.name]))==nodes
load.(['var',num2str(i)])=file.([s.name]);
else
warning(['Loaded file: ',load.(['var',num2str(i)]),' shows different size than the network, variable is set constant to general value']);
end
else
warning(['Loaded file: ',load.(['var',num2str(i)]),' data does not exist, variable is set constant to general value']);
% Set variable to general value from environment
environment.(char(load.(['var',num2str(i)])))=ones(nodes,1)*genValue.(['var',num2str(i)]);
end
end
Please help me out with that, btw, also manual loading (double klick in the editor) produces the same error...
Thanks to all!

Answers (2)

Shashank Sripad
Shashank Sripad on 1 Feb 2017
I'm facing the same issue with .mat files although they are only about 5KB. It works only if I clear the workspace and then load it, else it always gives me the same error. I use 3 .mat files, and if they are not loaded in a particular order, I get this error as well.
Would be super grateful to get some clarity on this issue.

Walter Roberson
Walter Roberson on 1 Feb 2017
load.(['var',num2str(i)])=file.([s.name]);
is overwriting the function load with a structure named load . That is a problem because you are inside a loop.

Community Treasure Hunt

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

Start Hunting!