1
votes

I have a 5-by-200 matrix where the i:50:200, i=1:50 are related to each other, so for example the matrix columns 1,51,101,151 are related to each other, and columns 49,99,149,199 are also related to each other.

I want to use a for-loop to create another matrix that re-sorts the previous matrix based on this relationship.

My code is

values=zeros(5,200);

for j=1:50
    for m=1:4:200
        a=factor_mat(:,j:50:200)
        values(:,m)=a
    end
end

However, the code does not work.

1
does not work is not a helpful summary of an issue. Please provide a minimal, functioning example and an example of inputs/outputs.excaza
@ AllenLi it looks like you have an indexing issue? can you post the error message as well as what excaza says?willpower2727

1 Answers

2
votes

Here's what's happening. Let's say we're on the first iteration of the outer loop, so j == 1. This effectively gives you:

j = 1;
for m=1:4:200
   a=factor_mat(:,j:50:200)
   values(:,m)=a;
end

So you're creating the same submatrix for a (j doesn't change) 50 times and storing it at different places in the values matrix. This isn't really what you want to do.

To create each 4-column submatrix once and store them in 50 different places, you need to use j to tell you which of the 50 you're currently processing:

for j=1:50
   a=factor_mat(:,j:50:200);
   m=j*4;    %// This gives us the **end** of the current range
   values(:,m-3:m)=a;
end

I've used a little trick here, because the indices of Matlab arrays start at 1 rather than 0. I've calculated the index of the last column we want to insert. For the first group, this is column 4. Since j == 1, j * 4 == 4. Then I subtract 3 to find the first column index.


That will fix the problem you have with your loops. But loops aren't very Matlab-ish. They used to be very slow; now they're adequate. But they're still not the cool way to do things.

To do this without loops, you can use reshape and permute:

a=reshape(factor_mat,[],50,4);
b=permute(a,[1,3,2]);
values=reshape(b,[],200);