How to Index Through a For Loop

45 views (last 30 days)
John Stulich
John Stulich on 9 Jul 2017
Commented: Andrei Bobrov on 9 Jul 2017
Hi,
How do you index specific values in a matrix using a for loop and make them match specific other matrix entries?
I'm trying to do this with any size matrix, thus using for loops.
Say I have this matrix:
B = [1 4 7 10; 2 5 8 11;3 6 9 12]
1 4 7 10
2 5 8 11
3 6 9 12
And I want it to look like this:
1 3 6 9
2 5 8 11
3 6 9 12
Where R1C4 = R3C3, R1C3 = R3C2, and R1C2 = R3C1 (where R1 stands for row 1, etc. and C4 stands for column 4, etc.)
I have this code so far:
A = zeros(3,4); % 3x4 zero matrix
x = 1:12; % values to populate matrix with
o = 3; % number of points per column i.e. number of rows
m = 4; % number of polynomials i.e. number of columns
s = length(A);
for i = 1:numel(A); % 1 to 12
A(i) = x(i); % Linear indexing on a 2D matrix
for j = s-1; % run the loop 3 times
A(o-(o-1),m) = A(o,(m-1));
%A(o-(o-1),m-1) = A(o,(m-2)); goal is to remove this line and use for loop only
%A(o-(o-1),m-2) = A(o,(m-3)); goal is to remove this line and use for loop only
end
end
I can get "Row 1 Column 4" (9) to match with "Row 3 Column 3" (9), but am unsure how to proceed with the for loop so I can make it expandable to include any size matrix.
Any suggestions?
Thanks.

Answers (1)

Andrei Bobrov
Andrei Bobrov on 9 Jul 2017
Edited: Andrei Bobrov on 9 Jul 2017
B = [1 4 7 10; 2 5 8 11;3 6 9 12];
A = B;
A(1,2:end) = A(3,1:end-1);
or
A = B;
A(1,2:end) = A(1,2:end) - 1;
  2 Comments
John Stulich
John Stulich on 9 Jul 2017
Edited: John Stulich on 9 Jul 2017
Thanks. This is good for the above 3x4 matrix.
What about for any size matrix?
Such as this one 4x7 matrix:
E = linspace(-2,2,28);
F = reshape(E,4,7);
G = F;
G(1,2:end) = G(4,1:end-1)
I modified the "3" index in A(1,2:end) = A(3,1:end-1) to a "4" index, but how can I write the code (for loop / while loop ?) so I don't need to keep modifying the index numbers, rather so that it will run the code based on minimal input i.e. input matrix dimensions and input value range (I used linspace for the value range).
Andrei Bobrov
Andrei Bobrov on 9 Jul 2017
A = B;
A(1,2:end) = A(end,1:end-1);

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!