Loop matrices into a structure - matlab

I'm not even sure if the title describes what I want to do, so let me try to elaborate.
Each iteration of the loop creates an X matrix. As it stands now, only the final iteration of the X matrix remains after the loop finishes.
However my desired final output is 6 X matrices. One for each of the loop iterations.
Basically, I want to save all 6 of the X matrices, not overwrite them after each iteration.
for col=2:7
logprice=log(ret(1:end,col));
logret=diff(logprice);
exret=logret-logRFree;
price_mat(:,col-1)=logprice;
ret_mat(:,col-1)=logret;
exret_mat(:,col-1)=exret;
X=[ret_mat(:,col-1) termspread creditspread inflation realrate ];
end

If the size of X is different on each iteration (and it looks that way), it may be easiest to store them in a cell array:
% before loop
X = cell(N,1);
% in loop, with a counter ii ...
X{ii} = [...];
If the X matrix were the same size on each iteration of the loop, you could preallocate a 3D array and save to each slice (e.g. X=zeros(R,C,P); ... X(:,:,ii) = [...];);

There are two most common ways. Cell arrays is one of them. The other one is 3-D matrices. It can be generalized to n-D matrices too.
Cell arrays can handle different size of matrix X on every iteration. 3-D matrices cannot. All matrices have to be of the same size. You can pre-allocate cells as well as 3-D matrices to save execution time on large loops. Also, it is a good practice to follow.
Preallocate cell array
Preallocate matrix
It can be done as follows:
count=0;
for col=2:7
count=count+1;
logprice=log(ret(1:end,col));
logret=diff(logprice);
exret=logret-logRFree;
price_mat(:,col-1)=logprice;
ret_mat(:,col-1)=logret;
exret_mat(:,col-1)=exret;
%%%%%%Execute only one of the following two statements%%%%%%%
X{count}=[ret_mat(:,col-1) termspread creditspread inflation realrate ];
X(:,:,count)=[ret_mat(:,col-1) termspread creditspread inflation realrate ];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end

Related

Creating Multi Dimesnional Array from 1D array in Matlab?

Hello I am trying to create a simple array that contains a '10' 3x3 matrices. So I tried to create a 1D matrix that has 1 x 10 values. Then I tried assigning a 3x3 matrix in to each of the 10 slots in the 1D matrix. I am quite sure my syntax is wrong and matlab (I don't think allows this) but I couldn't find too much info to pre assign such array and I just started learning about matlab. Here is my attempt:
big_array = zeros(1,10) # creates 1x10 1d array
for i = 1:10
big_array(i) = zeros(3,3); #supposedly? assign 3x3 matrix in to each of the 10 slots
end
big_array # received an error
If you know that you want an array of 10 3x3 matrices, you would typically want to use a multidimensional array from the start.
big_array = zeros(10,3,3);
You can access the i'th matrix using big_array(i,:,:).
If you really do want a one-dimensional array of 3x3 matrices, you need to use a cell array.
big_array = {};
for i = 1:10
big_array{i} = zeros(3,3);
end
big_array
You can now access the i'th matrix using big_array{i}.
A small clarification - If all your slots must contain submatrices with the same size, then you can use very simple expression:
big_array = zeros(3,3,10) % (first dimension - rows, second dimension - columns, third dimension - bands or arrays)

How to loop through each value in a 3D matrix?

I have a matrix, 10x10x40, that is storing information of an image through time, where the the rows and columns indicate the spectral value at a specific point, and the third dimension is time. So in other words, a 10x10 image at 40 points in time. I would like to loop through each row, column and view that pixel history (1,1,:), (1,2,:)....(10,10,:).
Here's what I'm doing now:
val = [];
for i = 1:10;
for j = 1:10;
for k = 1:length(timevector)
val(k) = my_matrix(i,j,k);
end
end
end
Since I want to iterate through each pixel in time and then save that data, what would be the best way to store the new value/time vectors? I want to end up with 100 pixel history vectors, right now I end with one, and it's because val is written over within the loop. I know it's not advised to create variables within a loop, so what is the best alternative? Should I look into storing the output as a structure? I've been staring at this and I have over-complicated everything.
Depending on the structure you prefer, you can also use matlab's functions reshape and num2cell to get the output in the following form:
Alternative 1:
A = reshape(A,[],10);
This will return a matrix (100x40) where each row is a pixel's history.
Alternative 2:
A = num2cell( reshape(A,[],40), 2)
This will return a cell array (100x1) where each cell contains a vector (40x1) with each pixel's history.
Alternative 3:
A = squeeze( num2cell( permute(A, [3,1,2]), 1) );
This will return a cell array (10x10) where each cell contains a vector (40x1) with each pixel's history.
Depending on what you want to do with it, you don't need to store them in separate vectors. You can just get one of these pixel history vectors, like so,
pixel_history = squeeze(my_matrix(1,1,:));
squeeze will remove the singleton dimension from the slice, and make it into a 40-by-1 vector, instead of a 1-by-1-by-40 matrix.
To make the time dimension the first matrix dimension, you could also permute the matrix,
permute(my_matrix, [3 2 1]);
This will swap the 3rd and 1st dimensions, making the 1st dimension time.

How to raise a matrix to a vector of powers in matlab without for loop?

I have a 2x2 matrix that I want to multiply by itself 10 times while storing the result after each multiplication. This can easily be done with a for loop but I would like to vectorize it an eliminate the for loop. My approach was to have my 2x2 matrix a and raise it to a vector b with elements 1:10. The answer should be a 2x2x10 matrix that replicates typing
a^b(1)
a^b(2)
.
.
.
a^b(10)
To clarify I'm not doing this element wise I need actual matrix multiplication, and prefer not to use a for loop. Thanks for any help you can give me.
here is the code for you. I use the cellfun to do this and I have comments after each line of the code. It can compute and store from fisrt - nth order of the self-multiplication of an arbitrary matrix m. If you have any question, feel free to ask.
function m_powerCell = power_store(m, n) %m is your input matrix, n is the highest power you want to reach
n_mat = [1:n]; %set a vector for indexing each power result in cell
n_cell = mat2cell(n_mat,1,ones(1,n)); %set a cell for each of the power
m_powerCell = cellfun(#(x)power(m, x), n_cell, 'uni', 0); %compute the power of the matrix
end
%this code will return a cell to you, each element is a matrix, you can
%read each of the matrix by m_powerCell{x}, x represents the xth order

storing and accessing with matrices of more than two dimensions

I am using ode45 to solve a system with 4 variables. For each time I execute the code:
[t y] = ode45(#func, tspan, y0);
t will be a one dimensional matrix, while y will be a 2 dimensional matrix, with 4 columns, each of which is the solution for one of the variables in question.
I want to run multiple trials of this, and keep them in a 3D matrix my_y_results and my_t_results. I want to be able to, for example, plot the final value of a certain variable for a particular initial condition, as I change the initial condition. How would I do this?
So, on each iteration of the loop below, I want to place the new values in a new matrix.
for i = 1:1:10
y0 = **some value**
[t_temp, y_temp] = ode45(#func, tspan, y0);
my_t_results = **something**
my_y_results = *something* //your code here
end
Also, how would I access the different values after setting them? For example, to get the last value of the variable y(1) for each of the 10 trials, what code would I use?
Higher dimensions can be accessed similar to the usual row and column dimensions. Let's assume t is Nx1 and y is Nx4, and that we are running M trials (note that each trial will have to have the same number of points, N, in order to store the data in a 3-dimensional array).
Your array my_t_results doesn't have to be 3-dimensional and can simply be NxM, where each column is the time vector for a different trial.
The array my_y_results would be Nx4xM and can be defined in MATLAB with:
my_y_results = zeros(N,4,M);
At the end of each i'th trial you would store the results like this:
my_y_results(:,:,i) = y;
And of course accessing the data is similar:
y_i = my_y_results(:,:,i);

Storing output from each for loop iteration in MATLAB

Say I have 3 matrix data files in a folder..
I have a function (clustering_coef_bu) which calculates the clustering coefficient of a 2D matrix (data; has the dimensions 512x512) file. The output vector of the function creates a 512x1 Matrix (Clustering Coefficient), in double format.
With the for loop below, for each matrix (data) I'm calculating the clustering coefficient. However, I am having difficulties being able to store the output clustering coefficient for each run of the for loop. It would be ideal to output the clustering coefficient of each matrix into one singular structure. I.e a cell array, which has the dimensions 512x3.
for k = 1:3
ClusteringCoefficient=clustering_coef_bu(data)
end
Any help would be great. Thanks.
Something like this would probably help you:
widthArray = 3;
ClustingeringCoefficient = zeros(size(data, 1), widthArray);
for k = 1:widthArray
ClusteringCoefficient(:, k) = clustering_coef_bu(data); % a 512x3 double matrix
end