I'm trying to do a simple processing in Mathematica. My original code was in MATLAB. Part of the computation is the Gram-Schmidt process, which is an iterative calculation. Every vector is changed according to its predecessors. I hold all vectors as rows of a matrix.
- $r1' = r1 / |r1|$
- $r2' = r2 - (r2.r1')r1'/|r2 - (r2.r1')r1'|$
- $r3' = r3 - (r3.r2')r2' - (r3.r1')r1' / \text{norm-of-the-numerator}$
- ...
Now, it is clear that, for example
$$r2' = r2 - (r2.r1 / |r1|)r1 / |r1|/|r2 - (r2.r1 / |r1|)r1 / |r1||$$
since I replaced $r1'$ according to (1). If I understand Mathematica correctly, it remembers all this stages. So when I get to (6) $r6' = \ldots$ the computations is taking too long. I aborted after a few minutes, I have to get up to 11.
How can I deal with it? I read about memoization and tried it. This is what I wrote
gsstep[mat_, v_, rr_] :=
(lp = v.mat[[rr]];
lv = v - lp*mat[[rr]];
lv)
For[r = 1, r <= dw1, r++,
Print["r = ", r]
Clear[v];
v = mW[[r]];
For[rr = 1, rr <= r - 1, rr++, v = gsstep[mW, v, rr]];
Print["done"];
norm = Norm[v];
mW[[r]] = v/norm;];
Unfortunately, this didn't do the trick.
Can someone please give me some direction about what the correct way to do this in Mathematica?
Orthogonalize
? It does an automatic Gram-Schmidt orthogonalization. $\endgroup$Ortogonalize[ ]
? $\endgroup$