Hello,
I need help with this Mata task: Write a Mata function returning the sum of all odd elements of a vector (e.g. if the vector is x={1,2,4,7,5,6}, the function should return the solution of 1+4+5). The function should work for both column and row vectors (i.e. you need to use an if condition in your code). It is not necessary to embed this function in a Stata program. A simple Mata function for the use in Mata is sufficient.
Is the following function correct:
clear mata
mata
function task3(real vector x) {
real scalar i
real scalar n
real scalar r
real scalar c
r = rows(x)
c = cols(x)
if (c == 1) {
n = r
X=J(1,1,.)
}
if (r == 1) {
n = c
Y=J(1,1,.)
}
for(i=1; i<=n; i = i + 2) {
X = sum(i+i)
Y = sum(i+i)
}
return(X)
return(Y)
}
x = (1,2,4,7,5,6)
task3(x)
end
Thanks,
Ibrahim
I need help with this Mata task: Write a Mata function returning the sum of all odd elements of a vector (e.g. if the vector is x={1,2,4,7,5,6}, the function should return the solution of 1+4+5). The function should work for both column and row vectors (i.e. you need to use an if condition in your code). It is not necessary to embed this function in a Stata program. A simple Mata function for the use in Mata is sufficient.
Is the following function correct:
clear mata
mata
function task3(real vector x) {
real scalar i
real scalar n
real scalar r
real scalar c
r = rows(x)
c = cols(x)
if (c == 1) {
n = r
X=J(1,1,.)
}
if (r == 1) {
n = c
Y=J(1,1,.)
}
for(i=1; i<=n; i = i + 2) {
X = sum(i+i)
Y = sum(i+i)
}
return(X)
return(Y)
}
x = (1,2,4,7,5,6)
task3(x)
end
Thanks,
Ibrahim
Comment