How to Index Through a For Loop
47 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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.
0 commentaires
Réponses (1)
Andrei Bobrov
le 9 Juil 2017
Modifié(e) : Andrei Bobrov
le 9 Juil 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 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!