I think I’m going to learn a lot whith this question.
First, my principal goal is to transform any matrix according the following rule:
For each column, find the first element equal to 1.1. Suposse the position of this elememt is [n,j]. So, replaces all elemnts [n:end,j] with [n-1,j].
My scripts for this is the following:
function tabela_taxas(tab)
for j in 1:size(tab)[2]
aux = tab[:,j]
i = 1
while aux[i] != 1.1
i = i+1
end
element_aux = aux[i-1]
tab[i:end,j] .= element_aux
end
return tab
end
My first question, but not the most important, is that I think there is other way (more elegant) to writte the tabela_taxas function.
The second question is related to something strange. First, I will run the tabela_taxas function. For this, I’m going to simulate a specific matrix that allows me to test my function
You can see that the original matrix, tabela, has been modified. Which shouldn’t happen because the matrix tabela is an input and not an output. It’s as if I had done:
The input matrix is the output matrix – notice how your functions modifies and returns the input tab, without reassigning to it. If you don’t want to do this, you can add tab = copy(tab) to your function before modifying tab.
You can confirm that they’re the same matrix via tabela === tabela2.
For example:
function tabela_taxas!(tab) # mutating definition
for j in axes(tab, 2)
aux = @view(tab[:,j])
i = findfirst(==(1.1), aux)
i === nothing || (aux[i:end] .= aux[i-1])
end
return tab
end
# non-mutating
tabela_taxas(tab) = tabela_taxas!(copy(tab))