How do I index individual columns in an array?
조회 수: 26 (최근 30일)
이전 댓글 표시
Hi,
I have a fairly basic question that I cant seem to solve.
I have an array "high_perspective_taking" which has values from 0-4. I would like to write a for loop that goes through all the rows of columns 1 and 4 in order to change all the 4's to 0's, 3's to 1's, 1's to 3's, and 0's to 4's.
I have the following for loop but I am struggling on how to index both column 1 and column 4.
for p = 1:length(high_perspective_taking)
if high_perspective_taking(p,[1 4])== 0;
high_perspective_taking(p,[1 4])= 4;
end
if high_perspective_taking(p,[1 4])== 1;
high_perspective_taking(p,[1 4])= 3;
end
if high_perspective_taking(p,[1 4])== 3;
high_perspective_taking(p,[1 4])= 1;
end
if high_perspective_taking(p,[1 4])== 4;
high_perspective_taking(p,[1 4])= 0;
end
end
Thank you!
댓글 수: 0
채택된 답변
Voss
2022년 7월 22일
load high_perspective_taking.mat
% original:
high_perspective_taking
% 0 <-> 4, 1 <-> 3:
high_perspective_taking(:,[1 4]) = 4 - high_perspective_taking(:,[1 4])
댓글 수: 6
Voss
2022년 7월 23일
Well, if you're stil wanting to swap 0s with 4s and 1s with 3s, I would still use the approach in my answer, i.e.:
high_perspective_taking(:,[1 4]) = 4 - high_perspective_taking(:,[1 4])
In my comment I wanted to show a more general approach to swapping values where the relation was not necessarily as simple as x = 4-x, but you're right I neglected to show how to apply that approach only to certain columns.
Probably the easiest way would be to create a temporary variable containing just the relevant columns, then do the swapping in that variable, then assign back to the original variable. For example:
% a matrix where 0s and 4s in columns 1 and 4 will be swapped:
A = [0 0 0 0; 0 1 2 3; 1 2 3 4; 4 4 4 4]
% temporary variable containing just columns 1 and 4 of A:
A14 = A(:,[1 4]);
% swap 0s and 4s in A14:
A14_is_zero = A14 == 0;
A14_is_four = A14 == 4;
A14(A14_is_zero) = 4;
A14(A14_is_four) = 0;
% assign back to A:
A(:,[1 4]) = A14
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!