0
votes

I would like to use a for loop within a for loop (I think) to produce a number of vectors which I can use separately to use polyfit with.

I have a 768x768 matrix and I have split this into 768 separate cell vectors. However I want to split each 1x768 matrix into sections of 16 points - i.e. 48 new vectors which are 16 values in length. I want then to do some curve fitting with this information.

I want to name each of the 48 vectors something different however I want to do this for each of the 768 columns. I can easily do this for either separately but I was hoping that there was a way to combine them. I tried to do this as a for statement within a for statement however it doesn't work, I wondered if anyone could give me some hints on how to produce what I want. I have attached the code.

Qne is my 768*768 matrix with all the points.

N1=768;
x=cell(N,1);

for ii=1:N1;
   x{ii}=Qnew(1:N1,ii);
end 

for iii = 1:768;
   x2{iii}=x{iii};
    for iv = 1:39
    N2=20;        
    x3{iii}=x2{iii}(1,(1+N2*iv:N2+N2*iv));
    %Gx{iv}=(x3{iv});
    end     
end
1
Is your code Matlab/Octave code? If so, then consider tagging your question matlab.thb
Thank you very much. It's MATLAB. Thanks for the advice. This is the first time I've used this website. :)user1423578
What is exactly the problem? btw I notice one error - in the line xr{iii}=... you should check that the index is in the range (it should be maximal 768?)bdecaf
??? Index exceeds matrix dimensions. Error in ==> heightmatrixworkingchange at 333 x3{iii}=x2{iii}(1,(1+N2*iv:N2+N2*iv)); The error I get is shown above. I wanted to know the best way to split each vector into small vectors within each of the 768 vectors. I want to know where each vector lies for future use.user1423578

1 Answers

2
votes

Use a normal 2D matrix for your inner split. Why? It's easy to reshape, and many of the fitting operations you'll likely use will operate on columns of a matrix already.

for ii=1:N1
    x{ii} = reshape(Qnew(:, ii), 16, 48);
end

Now x{ii} is a 2D matrix, size 16x48. If you want to address the jj'th split window separately, you can say x{ii}(:, jj). But often you won't have to. If, for example, you want the mean of each window, you can just say mean(x{ii}), which will take the mean of each column, and give you a 48-element row vector back out.

Extra reference for the unasked question: If you ever want overlapping windows of a vector instead of abutting, see buffer in the signal processing toolbox.

Editing my answer:

Going one step further, a 3D matrix is probably the best representation for equal-sized vectors. Remembering that reshape() reads out columnwise, and fills the new matrix columnwise, this can be done with a single reshape:

x = reshape(Qnew, 16, 48, N1);

x is now a 16x48x768 3D array, and the jj'th window of the ii'th vector is now x(:, jj, ii).