Charlie Crown
Charlie Crown

Reputation: 1089

Make a row or column of a matrix all zero's [Julia]

I want to make all values in a row or column of a Matrix zero's (Float64 in this case) without resorting to a manual for loop.

fill! and zero work on the entire matrix, but not on an individual column or row (at least my attempts have failed... ie., fill!(tester[:,1],0.0) doesn't work.

Here is an example of the manual method

tester = [[22.2 33.3  44.4]; [44.4  55.5 66.6]; [77.7 88.8 99.9] ]

for i = 1:size(tester,1)
    tester[i,1] = 0.0
end

the output for the initialization and modification is

[22.2 33.3 44.4; 44.4 55.5 66.6; 77.7 88.8 99.9]  <-- Initial matrix
[0.0 33.3 44.4; 0.0 55.5 66.6; 0.0 88.8 99.9]     <-- Correct change

A comprehension can probably be used to make the for loop look a little tidier, but that is just cosmetics. I am wondering if there is an actual function like fill! or zero that can be used?

Upvotes: 1

Views: 1179

Answers (1)

hckr
hckr

Reputation: 5583

Simply use array indexing with : to select all the entries along the dimension you choose and .=.

julia> tester = [22.2 33.3 44.4; 44.4 55.5 66.6; 77.7 88.8 99.9];

julia> tester[:,1] .= 0.0;

julia> tester
3×3 Array{Float64,2}:
 0.0  33.3  44.4
 0.0  55.5  66.6
 0.0  88.8  99.9

For more about indexing an array, you might find it useful to read the relevant manual entry.

Upvotes: 5

Related Questions