saving a matrix from a loop into a structure

1 view (last 30 days)
tyler estrada
tyler estrada on 5 Oct 2018
Commented: KSSV on 5 Oct 2018
I am loading several matlab files in a loop. then taking specific information from the matlab file and cropping the information (becuase they are zeros). I would like to then save the cropped information from each matlab file into a new structure. everything works upto putting the cropped information into the new structure. im sure this is an easy fix, but i havent been able to fix it yet.
%pre-allocate space
L=zeros(1,X1);
am=zeros(1,X1);
for i=1:X1
%load each matlab file in path described
L=load([mypath,testname,'\',myname,'\ResFiles\ncorrFullstraindata_rs_',myfilenames{i},'.mat']);
%grab specific matrix out of matlab file
a=L.data_dic_save.strains(120).plot_eyy_cur_formatted;
%cropp matrix
a=flipud(a);
a=a(any(a,2),:); %removes rows with only zeros
a=a(:,any(a,1)); %removes columns with only zeros
%%%Having troubles on this section
%for each file save a matrix to a structure
am{i}= a(i);
%rotate matrix
at{i}=am(i)';
path=([mypath,testname,'\',myname '\ResFiles\ncorrCroppedstraindata_rs_',myfilenames{i},'.mat']);
end
  3 Comments
Stephen23
Stephen23 on 5 Oct 2018
Edited: Stephen23 on 5 Oct 2018
I don't see how "everything works upto putting the cropped information into the new structure", because before the loop you defined am as numeric, but then inside the loop try to allocate to it as if it was a cell array, using curly braces.
In any case, what is the exact problem that you getting? Does the wrong data get saved? Do you get an error (if so, what is the complete error message?)? Does MATLAB go into an infinite loop? Does your laptop catch fire? Should I call the fire brigade?
Note that to construct a file path you should use fullfile rather that concatenating strings.
Also do NOT use path as a variable name, because this shadows the very important inbuilt path function.
KSSV
KSSV on 5 Oct 2018
Ohh..yes..am should initialized as:
am=cell(1,X1);
instead of
am=zeros(1,X1);

Sign in to comment.

Answers (2)

ANKUR KUMAR
ANKUR KUMAR on 5 Oct 2018
I hope this simple example helps you to resolve your problem of saving a matrix in a structure from a loop.
clc
clear
for i=1:100
struc_A.X=randi(100,50,50);
struc_A.Y=magic(randi(20,1,1));
end

KSSV
KSSV on 5 Oct 2018
May be you should use this:
am{i}= a(i);
%rotate matrix
at{i}=am{i}';

Community Treasure Hunt

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

Start Hunting!