How to apply a function only to the second column of a matrix

How to apply a function only to the second column of a matrix

The only way I know of is this. Is there an easier way to apply the sin function to only the second column of a matrix?

julia> m = [1. 2. 3.; 4. 5. 6.; 7. 8. 9. ]
3×3 Array{Float64,2}:
 1.0  2.0  3.0
 4.0  5.0  6.0
 7.0  8.0  9.0

julia> for k = 1:size(m)[1]
           m[k,2] = sin(m[k,2])
       end

julia> m
3×3 Array{Float64,2}:
 1.0   0.909297  3.0
 4.0  -0.958924  6.0
 7.0   0.989358  9.0

How about @views m[:,2] .= sin.(m[:, 2]). This will also work without the @views but then will be making a copy with m[:, 2].

1 Like
julia> m = [1. 2. 3.; 4. 5. 6.; 7. 8. 9. ]
3×3 Array{Float64,2}:
 1.0  2.0  3.0
 4.0  5.0  6.0
 7.0  8.0  9.0

julia> @views m[:,2] .= sin.(m[:, 2])
3-element view(::Array{Float64,2}, :, 2) with eltype Float64:
  0.9092974268256817
 -0.9589242746631385
  0.9893582466233818

julia> m
3×3 Array{Float64,2}:
 1.0   0.909297  3.0
 4.0  -0.958924  6.0
 7.0   0.989358  9.0