0

I have a matrix that was stored in a .mat file, and was then reloaded in matlab via the function matfile. I also have a logical index, like logical([1 0 1 0]), that I want to apply to the loaded matrix:

results = matfile('results.mat');
% id is my logical vector of the appropriate size
% IV is a matrix stored in results.mat
newIV = results.IV(:,id);  

However, I am running into a problem and getting this error:

'IV' cannot be indexed with class 'logical'. Indices must be numeric.

I do not understand what is causing this issue. I have been using this same code before and it was working, the only thing was that I did not have to load the struct results before, I already had it in memory. It gets weirder; this works:

IV = results.IV;
newIV = IV(:,id); % this works somehow

This also works:

results_raw = matfile('results.mat');
results = struct('IV',results_raw.IV);
newIV = IV(:,id); % this also works!!! why matlab, why???

I also tried resaving the results.mat file using the -v7.3 flag, but it did not solve the problem. The issue seems to be with loading the .mat file, because I created a struct with a matrix and used logical indexing and it worked fine.

Question: why does indexing work when I pass results.IV to IV? how can I make it work with results.IV?

Thanks for helping!!! :D

Guilherme Salomé
  • 1,899
  • 4
  • 19
  • 39
  • 3
    Seems you can not, like other limitations, as documented explicitly in the `matfile` page: https://www.mathworks.com/help/matlab/ref/matfile.html#bt2ft8s-6 When you assign the data to another variable, it states as a new data type, with all the data in the workspace, has nothing to do with `matfile`. – Adiel Sep 18 '17 at 06:13

1 Answers1

1

As @Adiel said in questions comments. You can't use logical indices. So, convert logical indices to numeric indices using find.

results = matfile('results.mat');
% id is my logical vector of the appropriate size
% IV is a matrix stored in results.mat
newIV = results.IV(:,find(id));  
Rijul Sudhir
  • 2,064
  • 1
  • 15
  • 19
  • This will only work if `id` is of the same dimension of `results.IV`. Since `results.IV` is a matrix, we would need `id` to be a matrix so that `find(id)` works as intended. If `id` is a vector, in the case of linear indexing, then even `find(id)` will not work, as `matfile does not support linear indexing`. The solution seems to be copying `results.IV` to a matrix in the workspace. – Guilherme Salomé Sep 18 '17 at 19:02