Search code examples
matrixelementoctaveoperation

How to change the elements by different values in a matrix simultaneously in Octave?


I want to change the individual elements in a matrix by different values simultaneously. How do I do that?

For example: I want to change the first element in matrix A by certain amount and the second element by a different amount simultaneously.

{ A = [1; 2]

% instead of doing A(1) = ..... A(2) = .....

}


Solution

  • You can access the elements of a vector or matrix and replace them.

    For a vector this is intuitive.

    octave:16> A = 1:9
    A =
    
       1   2   3   4   5   6   7   8   9
    
    octave:17> A([1 3 5 7 9]) = 0
    A =
    
       0   2   0   4   0   6   0   8   0
    

    This can be done for a matrix as well. The elements of a matrix are arranged in a column-first manner. You can use a single index to access the elements of a matrix.

    octave:18> A = [1 2 3; 4 5 6; 7 8 9]
    A =
    
       1   2   3
       4   5   6
       7   8   9
    

    The 2nd element of A is the same as A(2, 1). The 4th element of A is the same as A(1, 2).

    octave:21> A(2)
    ans =  4
    octave:22> A(4)
    ans =  2
    

    So, you can set all the odd elements of A to 0 in one go like this:

    octave:19> A([1 3 5 7 9]) = 0
    A =
    
       0   2   0
       4   0   6
       0   8   0