Octave Gauss Jordan - math

I have been trying to do Gauss jordan method in matrices in octave, and I have found diferent ways to call the function, but none works. How can I do that?
A=[1 -2 -1; -1 1 1; 1 1 5]
B=[1; 4; -3]
#format rat
#Transposta = transpose(A) #Transposta
#Inversa = inv(A) #Inversa
#Adjunta = det(A)*inv(A) #Adjunta se A tiver inversa
determinante = det(A) #Determinante.
Resultado = Gaussian(A)

Use the rref function...
A = [1 -2 -1; -1 1 1; 1 1 5]
B = [1; 4; -3]
C = [A, B]
[a, b] = rref(C)
Result
a = 1.0000 0 0 -7.1667
0 1.0000 0 -5.0000
0 0 1.0000 1.8333
More Info: https://docs.octave.org/v7.3.0/Basic-Matrix-Functions.html

Related

How to efficiently store calculations from different combinations of variables and factor levels in a data frame?

I'm hoping to get some help on writing some more efficient code for a particular task that I'm doing. My example may be a little complicated, so I'll do my best to explain it. Essentially, I'm wanting to perform some precision (p), recall (r) and F1 (f) calculations based on the levels of a factor variable (ex$v) and for each combination of targets and predictions. Here is my example data.
# Example data.
set.seed(100)
ex <- data.frame(
v = c(rep("slo", 50), rep("mod", 50), rep("fas", 50)),
sr = c(rep(c(100, 800), 75)),
A = rbinom(150, 1, 0.8),
B = rbinom(150, 1, 0.8),
C = rbinom(150, 1, 0.8),
D = rbinom(150, 1, 0.8),
E = rbinom(150, 1, 0.8)
)
ex$v <- as.factor(ex$v)
So far, I have attempted to write a function that quickly manipulates ex to create a custom confusion matrix. In this particular example, A is my target and B is my prediction for ex$v[slo] only. Initially, I wrote this function to save repeating the dplyr lines of code for subsequent combinations of targets and predictions.
# Function to create custom confusion matrix.
f <- function(dat, sp, hz, target, pred){
dat %>%
filter(v == sp & sr == hz) %>%
select(target, pred) %>%
table() %>%
as_data_frame()
}
# Test function.
test <- f(dat = ex, sp = "slo", hz = 100, target = "A", pred = "B")
In this isolated example, I then calculate precision (p), recall (r) and F1 (f) from test using these three lines of code.
# Precision/recall/F1 calculations.
p <- test$n[4] / (test$n[4] + test$n[2])
r <- test$n[4] / (test$n[4] + test$n[3])
f <- 2 * (p * r) / (p + r)
This gives me the scores for A and B, but I want to repeat this process for six more combinations of targets and predictions and for each level of ex$v and store these in a tibble/data.frame. However, I only want A and B to be my targets. This is where I'm stuck. I'm wondering whether there is a way to formulate the code into a loop or in some other way that makes this process a bit more efficient, rather than continually repeating the lines of code shown here and joining each separate output manually. I'd like the tibble to look something like the example below, where .x, .y and .z would represent each level of ex$v, which are different speeds.
Comp p.x r.x f.x p.y r.y f.y p.z r.z f.z
B - A 0 0 0 0 0 0 0 0 0
C - A 0 0 0 0 0 0 0 0 0
D - A 0 0 0 0 0 0 0 0 0
D - A 0 0 0 0 0 0 0 0 0
C - B 0 0 0 0 0 0 0 0 0
D - B 0 0 0 0 0 0 0 0 0
E - B 0 0 0 0 0 0 0 0 0
I hope that all makes sense. Any help with this will be fantastic.
Thanks.
Here's an option which gives the output in a long format.
library(tidyverse)
f <- function(dat, sp, hz, target, pred){
test <- dat %>%
filter(v == sp & sr == hz) %>%
select(target, pred) %>%
table() %>%
as.data.frame()
p <- test$Freq[4] / (test$Freq[4] + test$Freq[2])
r <- test$Freq[4] / (test$Freq[4] + test$Freq[3])
f <- 2 * (p * r) / (p + r)
tibble(sp, hz, target, pred, p, r, f)
}
cols <- names(ex)[-(1:2)]
crossing(as.data.frame(t(combn(cols, 2))), v = unique(ex$v), sr = unique(ex$sr)) %>%
pmap_df(~f(dat = ex, sp = ..3, hz = ..4, target = ..1, pred = ..2))
# sp hz target pred p r f
# <fct> <dbl> <chr> <chr> <dbl> <dbl> <dbl>
# 1 fas 100 A B 0.895 0.739 0.810
# 2 fas 800 A B 0.8 0.842 0.821
# 3 mod 100 A B 0.789 0.75 0.769
# 4 mod 800 A B 0.870 0.952 0.909
# 5 slo 100 A B 0.826 0.95 0.884
# 6 slo 800 A B 0.706 0.632 0.667
# 7 fas 100 A C 0.737 0.7 0.718
# 8 fas 800 A C 0.65 0.765 0.703
# 9 mod 100 A C 0.737 0.7 0.718
#10 mod 800 A C 0.957 0.917 0.936
# … with 50 more rows
combn creates all combinations of names and using crossing we also create every combination of unique v and sr values which are passed to the f function.

How to rotate plot along x-axis in Scilab?

Please can anyone tell me how to rotate it along the x-axis .
Rotate curve C1(u) about X-axis to generate the set of curves at a step size of pi/100 given by
theta=0:%pi/100:%pi/2.
ABC = [0 0 1;1 1 1;1/4 1/2 1] \ [0 0 0;1 0 0;1/2 1/2 0];
A = ABC(1,:);
B = ABC(2,:);
C = ABC(3,:);
u = linspace(0,1,100);
C1 = A'*u.^2+B'*u+C'*ones(u);
param3d(C1(1,:),C1(2,:),C1(3,:));
This will do the job:
ABC = [0 0 1;1 1 1;1/4 1/2 1] \ [0 0 0;1 0 0;1/2 1/2 0];
A = ABC(1,:);
B = ABC(2,:);
C = ABC(3,:);
u = linspace(0,1,100);
C1 = A'*u.^2+B'*u+C'*ones(u);
param3d(C1(1,:),C1(2,:),C1(3,:));
theta = %pi/100;
R = [1 0 0
0 cos(theta) -sin(theta)
0 sin(theta) cos(theta)];
for i=1:50
C1 = R*C1;
param3d(C1(1,:),C1(2,:),C1(3,:));
end
clc;clear;
theta=0:%pi/100:%pi/2;
n=length(theta);
for i=1:n
x=sin(theta(i));
y=cos(theta(i));
r=[1 0 0;0 y -x;0 x y];
ABCD = [0 0 1;1 1 1;1/4 1/2 1] \ [0 0 0;1 0 0;1/2 1/2 0];
ABC = ABCD*r';
A = ABC(1,:);
B = ABC(2,:);
C = ABC(3,:);
u = linspace(0,1,100);
C1 = A'*u.^2+B'*u+C'*ones(u);
param3d(C1(1,:),C1(2,:),C1(3,:));
end

Floyd Warshall algorithm with adjacency matrix

I'm trying to implement the floyd warshall algorithm but it won't work correctly.
What I want is the shortest path distances from one vertex to another written in a matrix d and the predecessors in a matrix pred. The input is an adjacency matrix which contains all of the edge weights.
function FloWa(C)
N = size(C)
n = min(C[1],C[2])
pred = -1*ones(C[1],C[2])
d = C
for k in 1:n
for i in 1:n
for j in 1:n
if d[i,j] > d[i,k] + d[k,j]
if pred[i,k] == -1
pred[i,j] = k
else
pred[i,j] = pred[k,j]
end
d[i,j] = d[i,k] + d[k,j]
end
if i == j && d[i,i] < 0
println("negative Dicycle")
end
end
end
end
return d, pred
end
When i am running my code with the matrix
A = [0 2 1 4 5 1; 1 0 4 2 3 4; 2 1 0 1 2 4; 3 5 2 0 3 3; 2 4 3 4 0 1; 3 4 7 3 1 0]
i don't get the right results.
For d i get the same matrix as A and pred is printed as an Array{Float64}(0,1).
I have not checked the implementation of the algorithm, but you seem to initialize pred and d incorrectly. Here is a way to do it that is I assume you indented:
n = size(C, 1) # get number of rows in C
#assert n == size(C, 2) # make sure that C is square or throw an error
pred = fill(-1, size(C)) # fill pred with -1 and make it have the same size as C
d = copy(C) # d is a copy of C

How to code quadruple loops in R? Or do it in Matrix way?

I am trying to code methods in this
paper
in R. But I am stuck at their equation 7a and 7b.
Suppose we have a site by species matrix and a functional traits matrix
for species. We then can calculate distances between species.
library(FD)
data(dummy)
base = exp(1)
(dis = as.matrix(gowdis(dummy$trait)))
## sp1 sp2 sp3 sp4 sp5 sp6 sp7 sp8
## sp1 0.0000 0.2182 0.5240 0.6737 0.5291 0.6100 0.4484 0.4073
## sp2 0.2182 0.0000 0.6678 0.5610 0.8146 0.5933 0.6863 0.2039
## sp3 0.5240 0.6678 0.0000 0.8226 0.4862 0.2785 0.4849 0.5959
## sp4 0.6737 0.5610 0.8226 0.0000 0.4843 0.7074 0.5575 0.2391
## sp5 0.5291 0.8146 0.4862 0.4843 0.0000 0.6067 0.3023 0.5586
## sp6 0.6100 0.5933 0.2785 0.7074 0.6067 0.0000 0.6188 0.4470
## sp7 0.4484 0.6863 0.4849 0.5575 0.3023 0.6188 0.0000 0.7030
## sp8 0.4073 0.2039 0.5959 0.2391 0.5586 0.4470 0.7030 0.0000
(comm = dummy$abun)
## sp1 sp2 sp3 sp4 sp5 sp6 sp7 sp8
## com1 1 1 0 0 4 2 0 0
## com2 0 0 0 2 1 0 0 5
## com3 2 0 0 0 0 1 0 3
## com4 1 0 7 0 0 0 0 0
## com5 0 0 2 3 3 0 0 0
## com6 0 3 0 0 5 6 1 6
## com7 3 5 0 3 0 0 0 0
## com8 0 0 0 0 6 2 1 2
## com9 4 1 1 3 0 0 2 0
## com10 0 4 1 0 0 0 6 1
In this example, we have 10 sites and 8 species.
Here are the equations I want to code:
(source: plos.org)
(source: plos.org)
N is the total number of sites (10 here); Qz++2 is a constant;
d_ij is dis[i,j]; z_ik is the abundance of species i in site k
dummy$comm[k,i]; q is a positive number.
I think I can code them in loop. There must be a better way than a
loop to do this. Matrix manipulation?
My loop for q = 1:
N = nrow(comm)
S = ncol(comm)
comm_gamma = colSums(sweep(comm, 1, rowSums(comm, na.rm = TRUE), "/"))/N
comm_alpha = sweep(comm, 1, rowSums(comm, na.rm = TRUE), "/")
dij = dis^2
Q_gamma = as.vector(comm_gamma %*% dij %*% matrix(comm_gamma, ncol = 1)) # Rao's Q for pooled assemblage.
FD_q_gamma = exp(-1 * sum(dij *
(outer(comm_gamma, comm_gamma, FUN = "*")/Q_gamma) *
log(outer(comm_gamma, comm_gamma, FUN = "*")/Q_gamma)))
# equa 6b in the paper.
# for q = 1
vv = vector("list", length = N)
for(k in 1:N){
vv[[k]] = vector("list", length = N)
for(m in 1:N){
vv[[k]][[m]] = vector("list", length = S)
for(i in 1:S){
vv[[k]][[m]][[i]] = vector("list", length = S)
for(j in 1:S){
xx = log((comm_alpha[k,i] * comm_alpha[m,j]/(Q_gamma * N^2)), base)
if(comm_alpha[k,i] == 0 | comm_alpha[m,j] == 0){
xx = 0
}
vv[[k]][[m]][[i]][[j]] = (dij[i,j] *
(comm_alpha[k,i] * comm_alpha[m,j]/(Q_gamma * N^2) *
xx
))
}
}
}
}
(FD_q_alpha_loop = exp(-1 * sum(unlist(vv), na.rm = T))/(N^2))
## [1] 2.336781
# use outer()
x = (outer(comm_alpha, comm_alpha, FUN = "*"))/(Q_gamma * (sum(comm_alpha)^2))
x[x==0] = NA
xx = x*log(x)
for(k in 1:N){
for(j in 1:S){
xx[,,k,j] = sweep(xx[,,k,j], 2, dij[j,], "*")
}
}
(FD_q_alpha_outer = exp(-1*sum(xx, na.rm=T))/N^2)
## [1] 2.336781
FD_q_alpha_loop == FD_q_alpha_outer
## [1] TRUE
(FD_q_beta = FD_q_gamma/FD_q_alpha_outer)
## [1] 6.966901
# beta diversity should be between 1 and N^2 (100 here)
Does my code seems correct? (It seems ok)
Thanks for your help!

The running time of my program in big O time

Can someone help me figure out the running time of this loop? I believe it is O(5nlogn).
for(int f = 0; f < Array.length; f++) {
F = Array[f];
for(int e = 0; e <= f; e++) {
E = Array[e];
for(int d = 0; d <= e; d++) {
D = Array[d];
for(int c = 0; c <= d; c++) {
C = Array[c];
for(int b = 0; b <= c; b++) {
B = Array[b];
for(int a = 0; a <= b; a++) {
A = Array[a];
}
}
}
}
}
}
Thanks
The answer is Θ(n6). I wrote a program to simulate the inner loop and record how many times a series of n executions occurs:
static void Main(string[] args)
{
int arrLength = 20;
int[] arr = new int[arrLength];
for (int f = 0; f < arrLength; f++)
{
for (int e = 0; e <= f; e++)
{
for (int d = 0; d <= e; d++)
{
for (int c = 0; c <= d; c++)
{
for (int b = 0; b <= c; b++)
{
//for (int a = 0; a <= b; a++)
arr[b] = arr[b] + 1;
}
}
}
}
}
for (int i = 0; i < arr.Length; i++)
{
Debug.WriteLine(string.Format("{0} execution: {1} time(s).", i + 1, arr[i]));
Console.WriteLine(string.Format("{0} execution: {1} time(s).", i + 1, arr[i]));
}
Console.ReadLine();
}
Running this with an arrLength of 1 gives:
1 execution: 1 time(s).
Running this with an arrLength of 2 gives:
1 execution: 5 time(s).
2 execution: 1 time(s).
Running this with an arrLength of 3 gives:
1 execution: 15 time(s).
2 execution: 5 time(s).
3 execution: 1 time(s).
As it turns out, the execution times always follow the same equation. At arrLength of 20, we get:
1 execution: 8855 time(s).
2 execution: 7315 time(s).
3 execution: 5985 time(s).
4 execution: 4845 time(s).
5 execution: 3876 time(s).
6 execution: 3060 time(s).
7 execution: 2380 time(s).
8 execution: 1820 time(s).
9 execution: 1365 time(s).
10 execution: 1001 time(s).
11 execution: 715 time(s).
12 execution: 495 time(s).
13 execution: 330 time(s).
14 execution: 210 time(s).
15 execution: 126 time(s).
16 execution: 70 time(s).
17 execution: 35 time(s).
18 execution: 15 time(s).
19 execution: 5 time(s).
20 execution: 1 time(s).
Plugging this into the awesome Online Encyclopedia of Integer Sequences, we get the Binomial coefficient binomial(n,4), which is this (the sequence starts at an offset of 4):
binomial(n,4)
n*(n-1)*(n-2)*(n-3)/24
0 = 0
1 = 0
2 = 0
3 = 0
4 = 1
5 = 5
6 = 15
7 = 35
...
If we look at the execution patterns output by my program above, we can rewrite it using a summation and this binomial sequence. For each integer i between 1 and n inclusive, we have the (n - i + 4)th number in the binomial(n,4) sequence, then multiplied by i, as the total number of executions. This is expressed as the following:
Substituting j = n - i + 1, and realizing that j goes from n downto 1, we can rewrite this equation as:
Relying on Wolfram Alpha to figure out this equation, I plugged in sum (n-j+1)(j+3)(j+2)(j+1)*j/24, j = 1 to n, and it came up with:
This is very obviously Θ(n6), so that is our answer.
The final equation is actually binomial(n,6), so for m loops, the number of executions of the innermost loop is probably binomial(n,m). For a given number of m loops, we have:
A good way to do this is to think about the space you're iterating over. If you think about it, the loops will iterate over nonnegative integral valuesof (a, b, c, d, e, f) where
n > f ≥ e ≥ d ≥ c ≥ b ≥ a
Each of these iterations does O(1) work (all loops just assign a variable, which takes O(1) work), so the question is how many possible values there are that satisfy the above formula. I'm going to claim it's Θ(n6), and will try to justify this with the rest of my answer.
First, note that the value certainly isn't any more than O(n6). All of a, b, c, d, e, and f range between 0 and n-1, so there's at most n different values for each. Therefore, the maximum possible number of values they can have is n6. This is not a tight bound, but it's certainly an upper bound. That gives us that the runtime is at most O(n6).
If we want to get a tighter bound, we have to work harder. To do this, I'm going to use the following fact:
1k + 2k + 3k + ... + nk = Θ(nk)
This is the sum of a geometric series, which is where it comes from.
This means that
sum(f from 0 to n-1)
sum (e from 0 to f)
sum (d from 0 to e)
sum (c from 0 to d)
sum (b from 0 to c)
sum (a from 0 to b)
1
= sum(f from 0 to n-1)
sum (e from 0 to f)
sum (d from 0 to e)
sum (c from 0 to d)
sum (b from 0 to c)
Theta(b)
= sum(f from 0 to n-1)
sum (e from 0 to f)
sum (d from 0 to e)
sum (c from 0 to d)
Theta(c^2)
= sum(f from 0 to n-1)
sum (e from 0 to f)
sum (d from 0 to e)
Theta(d^3)
= sum(f from 0 to n-1)
sum (e from 0 to f)
Theta(e^4)
= sum(f from 0 to n-1)
Theta(f^5)
= Theta(n^6)
Hope this helps!

Resources