Trying to change columns in a Matrix

조회 수: 38 (최근 30일)
Justin Noland
Justin Noland 2021년 9월 12일
댓글: Dave B 2021년 9월 12일
So lets say I have an array = [1 2 3 4; 3 3 4 5; 4 4 4 7], a 3 by 4 matrix. I want to change a certain column for a specified row. so lets say I want to change the columns 1,3,2 of the corresponding rows 1,2,3. All of the columns im changing for the corresponding rows will be changed to a value of 10. So my ideal answer when printing out the new matrix should be [10 2 3 4; 3 3 10 5; 4 10 4 7]. I'm trying to not use any loops to save on run time. And I've tried doing something like this: array(1:3, [1,3,2]) = 10. But I got the result [10 10 10 4; 10 10 10 5; 10 10 10 7]. which is not the answer I want. Is it possible to do this without using any loops. Any help would be appreciated thanks!!

채택된 답변

Dave B
Dave B 2021년 9월 12일
Specifying rows and columns makes MATLAB point to rectangles: a(1:2,1:4) refers to rows 1 and 2, columns 1 through 4, i.e. MATLAB doesn't take pairs of row/column but a range.
To change non-neighboring values you can specify their index.
There are two ways to index values in a matrix, you can do it by row and column or by a linear index. (You don't need to know this to solve your problem, but...) The linear index looks like this:
a = [1 2 3 4; 3 3 4 5; 4 4 4 7];
reshape(1:numel(a),size(a))
ans = 3×4
1 4 7 10 2 5 8 11 3 6 9 12
MATLAB has a nice function called sub2ind to convert rows and columns to linear index, which will let you address the non-neighboring values that you want to change:
ind = sub2ind(size(a),[1 2 3],[1 3 2])
ind = 1×3
1 8 6
With that index in hand, it's easy to adjust the values:
a(ind) = 10
a = 3×4
10 2 3 4 3 3 10 5 4 10 4 7
  댓글 수: 2
Justin Noland
Justin Noland 2021년 9월 12일
Oh ok. The linear indexing is a cool feature. Im coming from c++, and java, and so im a little new to matlab. Thanks for the help!!!
Dave B
Dave B 2021년 9월 12일
sub2ind makes it easy but you could also have done something like: (cols-1)*height(a) + rows
(I only mention this because I often do a sub2ind-like or ind2sub-like calculation when I'm in c++)

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by