Begin
Begin

Reputation: 13

Load observations from a file and count them [Matlab]

I want to load all observations of X from a file Var, and get the total number of observations in matlab. I do not know if the observations are in vector or array form. This is my attempt:

    % Load observations of variable X
load Var
% Get total number of observations
count = 0;
L = length(___);
for i = L
    count = count + 1;
end
Ntot = count;

I don't know what to pass in as a parameter to the length function. I tried Var but didn't work. It's abstract because file Var is hidden.

Upvotes: 0

Views: 54

Answers (1)

il_raffa
il_raffa

Reputation: 5190

It is not clear the type of the variables stored in the Var file, nevertheless, as a general approach you can use the matfile to get the informatino about the variables stored in a ".mat" file.

Since matfile returns a MAT-file object as a struct, you can exploit the dynaminc definition of the struct filed names to get the info about the variable.

The folowing provides an example with three arrays stored in the Var.mat file; you should be able to adapt the example to your specific mat file

The comments in the code should describe how the code works.

% Define some variables
a=1:3
b=1:6
c=1:9

% Save them in a mat file
save("Var.mat","a","b","c")

% Create a MAT-file object
var_info=matfile("Var.mat")

% Retrieve the information about the variables saved in the mat file
var_names=fieldnames(var_info);

% Remove the first entry which ciontains the information about the Properties of the mat fle
var_names(1)=[];

% Get the number of the variables stored in the mat file
number_of_var=length(var_names)

% Initialize the counter
count=0;

% Loop through the var_info struct
% Exploit the dynamic definition of the names of the struct's fileds
for i=1:number_of_var
   % Count the length of the variables
   n=length(var_info.(var_names{i}));
   count=count+n;
   fprintf('The variable %s is an array of %d elements\n',var_names{i},n)
end
fprintf('The total is %d\n',count)

Upvotes: 0

Related Questions