anderkve / FYS3150

https://anderkve.github.io/FYS3150
26 stars 14 forks source link

max_offdiag_symmetric (Project 2, Problem 3) #48

Closed oysthaga closed 2 years ago

oysthaga commented 2 years ago

I am a bit confused by the code sketch for finding the max off-diagonal element. The function double max_offdiag_symmetric(const arma::mat& A, int& k, int& l) takes "int& k, int& l" as input, yet k and l are the indices of the max value that we are supposed to find. Further: the code sketch has the line // Initialize references k and l to the first off-diagonal element of A weren't k and l initialized when they were used as input? If we are supposed to initialize them as references to first off-diagnonal element here, what are we using as input?

evenmn commented 2 years ago

Hi, k and l are passed by reference, which means that they are updated globally (the value is directly changed at the correct memory address) when they are updated inside the function. There are two good reasons for doing this: First, you avoid copying the variable which saves both memory and computational time. Second, functions in C++ can only return one variable, so if you want to update more than one variable inside a function this is the way to go.

BTW: l and k need to be declared before the function call, but you do not need to assign values. Example code snippet:

arma::mat A = "1., 0., 0., 0.5; 0., 1., -0.7, 0.; 0., -0.7, 1., 0.; 0.5, 0., 0., 1.;";
int k, l;
double max_element = max_offdiag_symmetric(A, k, l);

Hope this clarifies, Even

oysthaga commented 2 years ago

I understand, thank you.