Trying to change columns in a Matrix

39 views (last 30 days)
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!!

Accepted Answer

Dave B
Dave B on 12 Sep 2021
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 Comments
Justin Noland
Justin Noland on 12 Sep 2021
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 on 12 Sep 2021
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++)

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!