user3460203
user3460203

Reputation: 27

Changing certain values in every row of a matrix in MATLAB

Let's say I have a matrix like this -

A = 1 2 3 4;
    5 6 7 8

I want to change certain values in every row but I want to keep some of them, for example I want to make first element in every row 0 and second element 1. However, I want to keep the rest as they were originally. Result would be like this -

A = 0 1 3 4; 
    0 1 7 8 

Thanks.

Upvotes: 0

Views: 1109

Answers (3)

Divakar
Divakar

Reputation: 221744

One-liner

A(:,1:2) = repmat([0 1],[size(A,1) 1]) 

Edit 1: Additionally, if you want to change the last column to some number say 9, then use this -

A(:,[1:2 end]) = repmat([0 1 9],[size(A,1) 1]) 

Edit 2: If you would like to extend it more number of columns, you might as well create an array of column indices and another array for the new values. This code might help you understand -

column_array = [1 2 6 7 8];
new_values_for_columns = [ 0 1 2 3 4];
A(:,column_array) = repmat(new_values_for_columns,[size(A,1) 1]) 

Upvotes: 0

Moreira
Moreira

Reputation: 586

In order to change certain values in every row you can use A(row,:) = newValue;

In your example, you should use A(1,:) = 0; and A(2,:) = 1;

Upvotes: 0

ewz
ewz

Reputation: 423

In your example, you want to change every row of a given column (ie. A(:,column) = newValue)

A = [1 2 3 4; 5 6 7 8]
A(:,1) = 0; A(:,2) = 1;

>> A

A =

 0     1     3     4
 0     1     7     8

Upvotes: 0

Related Questions