How can i fill a pre-allocated matrix 2D?

Hello everyone!
i hope you can help me.
My code is:
[A, B]=size(storage);
nan_matrix=NaN(500,1000);
for ii=1:A
for k=1:B
[x,y]=corr(....)
end
end
%put x-values in the nan_matrix and save this matrix
How?

6 Comments

What is the dimension of storage? What would be size of x, y?
If corr() is the builtin MATLAB function, then the outputs x,y are the pairwise coefficients and p-values of the inputs and why would you want to put those into one array to begin with?
Perhaps one might want to stack the two in 3D arrays to keep a group together, but I can't see pasting the two disparate variables into one array being a useful thing to do.
Tell us what your real objective is here and how you would intend to use this later on...
storage is a grid (500x1000)
I want to create a correlation map in which, to each point (A,B) of the map (and therefore of the nan matrix (500x1000)) I associate a correlation value x.
So, i create the nan matrix with the same dimension of storage.
After that, I calculate the correlation coefficients.
At the end, I want to store these values(numerical values and NaN values) in a NaN matrix and save the matrix.
Correlation of what to what?
MATLAB will return the array of correlations directly, you don't need other storage.
See the documentation for examples for corr or xcorr2 depending upon which precisely it is are looking for, linear correlation or cross-correlation.
For example:
[rho, p_val]=corr(x,y, 'type', 'spearman');
the x_dimension is: 300x4
So I preallocated a matrix:
nan_matrix=NaN(500,1000);
in which to store the various rho, otherwise every time the loop restarts for the next column of x, the results will be overwritten.
I can't figure out how to store the results in the pre-allocated matrix before the cycle restarts.
I can do this with an empty vector:
example:
[A, B]=size(storage);
empty_vector=[];
for ii=1:A
for k=1:B
[x,y]=corr(....)
empty_vecto=[empty_vector; x]
end
end
but not with a nan matrix of a particular size
[rho, p_val]=corr(x,y, 'type', 'spearman');
the x_dimension is: 300x4
So, what is y?
"If you input matrices X and Y, rho is a k1-by-k2 matrix, where k1 and k2 are the number of columns in X and Y, respectively. The entry rho(a,b) is the pairwise linear correlation coefficient between column a in X and column b in Y."
I still don't follow why you think you need other storage...

Sign in to comment.

Answers (1)

I'd use xcorr2().

2 Comments

? sorry, I am not an expert in matlab
It's a sliding window that gives you the correlation of one set of data with another. What were you thinking of doing when you had corr() inside the double nested for loop?

Sign in to comment.

Categories

Asked:

on 25 Jul 2021

Commented:

on 25 Jul 2021

Community Treasure Hunt

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

Start Hunting!