How to Index Through a For Loop
조회 수: 46 (최근 30일)
이전 댓글 표시
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
답변 (1개)
Andrei Bobrov
2017년 7월 9일
편집: Andrei Bobrov
2017년 7월 9일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!