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

**URL:** <https://discourse.julialang.org/t/how-to-apply-a-function-only-to-the-second-column-of-a-matrix/45988>\
**Category:** New to Julia\
**Created:** [September 3, 2020, 6:16am UTC](https://discourse.julialang.org/t/how-to-apply-a-function-only-to-the-second-column-of-a-matrix/45988 "2020-09-03T06:16:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![StevenSiew](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevensiew/32/218393_2.png) [@StevenSiew](https://discourse.julialang.org/u/StevenSiew)\
**Post date:** [September 3, 2020, 6:16am UTC](https://discourse.julialang.org/t/how-to-apply-a-function-only-to-the-second-column-of-a-matrix/45988/1 "2020-09-03T06:16:20Z")

</div>

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
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

```

---

<div class="post-metadata">

**Author:** ![Oscar\_Smith](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oscar_smith/32/25343_2.png) [@Oscar\_Smith](https://discourse.julialang.org/u/Oscar_Smith)\
**Post date:** [September 3, 2020, 6:19am UTC](https://discourse.julialang.org/t/how-to-apply-a-function-only-to-the-second-column-of-a-matrix/45988/2 "2020-09-03T06:19:38Z")

</div>

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]`.

---

<div class="post-metadata">

**Author:** ![StevenSiew](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevensiew/32/218393_2.png) [@StevenSiew](https://discourse.julialang.org/u/StevenSiew)\
**Post date:** [September 3, 2020, 6:54am UTC](https://discourse.julialang.org/t/how-to-apply-a-function-only-to-the-second-column-of-a-matrix/45988/3 "2020-09-03T06:54:30Z")

</div>

> [@Oscar\_Smith](#):
>
> @views m[:,2] .= sin.(m[:, 2])

```julia
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

```
