Load specific column from mat file

Hello, I got a mat file with a struct of different variables. Each variable got a 1X5 struct entry. MAT File:
a = [0 0 0 0 1]
b = [0 0 0 1 0]
c = [0 1 0 0 1]
My simulink model got different variants and each column of the matfile belongs to a variant. So I would like to load that mat file with only one column. Workspace:
a = 1
b = 0
c = 1
Is that possible? Greetings Lucas

Answers (2)

This is not possible in one command, but with a tiny function:
function [a,b,c] = LoadColumn(FileName, col)
Data = load(FileName);
a = Data.a(col);
b = Data.b(col);
c = Data.c(col);
end
This might look trivial - in fact, it is. Does it solve your needs? If not, what is the remaining problem?

4 Comments

I would like to extend that matfile also, therefore programming with the variable names isn't that useful.
I solved it now that way:
load('Mapping_Datein.mat');
mat.Field_Names = fieldnames(Dummy_Fzg);
mat.Cells = struct2cell(Dummy_Fzg);
mat.Variante = 1; % Wahl der Variante
mat.Number_Variables = length(mat.Cells);
mat.i = 1;
while(mat.i <= mat.Number_Variables)
mat.string_spare = char(mat.Field_Names(mat.i));
mat.Cell_spare = mat.Cells{mat.i,1};
eval([['Fzg.' mat.string_spare] '=' num2str(mat.Cell_spare(mat.Variante))]);
mat.i = mat.i + 1;
end
clear ('mat', 'Dummy_Fzg');
But I thank you for your fast answer.
@Lucas Maiß: Your code is very inefficient, because of the conversion between numeric and string, and back again. You should really:
  • load into a variable, as Jan Simon showed.
  • Use dynamic field names instead of slow, inefficient and buggy eval:
Then you could easily avoid all of those pointless and slow conversions. Or as an alternative, here is a simpler solution using structfun:
>> a = [0 0 0 0 1];
>> b = [0 0 0 1 0];
>> c = [0 1 0 0 1];
>> save('test.mat','a','b','c')
>> S = load('test.mat');
>> T = structfun(@(v)v(end),S,'UniformOutput',0);
>> T.a
ans = 1
>> T.b
ans = 0
>> T.c
ans = 1
That look good. Could you explain me what you are doing here: @(v)v(end)
@Lucas: @(v)v(end) is an anonymous function, which replies the last element of the input.
With a loop:
function S = LoadColumn(FileName, col)
S = load(FileName);
Field = fieldnames(S);
for iField = 1:numel(Field)
F = Field{iField};
S.(F) = S.(F)(end);
end
end

Sign in to comment.

Tags

Asked:

on 20 Nov 2017

Commented:

Jan
on 20 Nov 2017

Community Treasure Hunt

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

Start Hunting!