-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
Copy pathgeneric.jl
1407 lines (1174 loc) · 32.2 KB
/
generic.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This file is a part of Julia. License is MIT: https://julialang.org/license
## linalg.jl: Some generic Linear Algebra definitions
# For better performance when input and output are the same array
# See https://github.com/JuliaLang/julia/issues/8415#issuecomment-56608729
function generic_rmul!(X::AbstractArray, s::Number)
@simd for I in eachindex(X)
@inbounds X[I] *= s
end
X
end
function generic_lmul!(s::Number, X::AbstractArray)
@simd for I in eachindex(X)
@inbounds X[I] = s*X[I]
end
X
end
function generic_mul!(C::AbstractArray, X::AbstractArray, s::Number)
if _length(C) != _length(X)
throw(DimensionMismatch("first array has length $(_length(C)) which does not match the length of the second, $(_length(X))."))
end
for (IC, IX) in zip(eachindex(C), eachindex(X))
@inbounds C[IC] = X[IX]*s
end
C
end
function generic_mul!(C::AbstractArray, s::Number, X::AbstractArray)
if _length(C) != _length(X)
throw(DimensionMismatch("first array has length $(_length(C)) which does not
match the length of the second, $(_length(X))."))
end
for (IC, IX) in zip(eachindex(C), eachindex(X))
@inbounds C[IC] = s*X[IX]
end
C
end
mul!(C::AbstractArray, s::Number, X::AbstractArray) = generic_mul!(C, X, s)
mul!(C::AbstractArray, X::AbstractArray, s::Number) = generic_mul!(C, s, X)
"""
rmul!(A::AbstractArray, b::Number)
Scale an array `A` by a scalar `b` overwriting `A` in-place.
# Examples
```jldoctest
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> rmul!(A, 2)
2×2 Array{Int64,2}:
2 4
6 8
```
"""
rmul!(A::AbstractArray, b::Number) = generic_rmul!(A, b)
"""
lmul!(a::Number, B::AbstractArray)
Scale an array `B` by a scalar `a` overwriting `B` in-place.
# Examples
```jldoctest
julia> B = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> lmul!(2, B)
2×2 Array{Int64,2}:
2 4
6 8
```
"""
lmul!(a::Number, B::AbstractArray) = generic_lmul!(a, B)
"""
cross(x, y)
×(x,y)
Compute the cross product of two 3-vectors.
# Examples
```jldoctest
julia> a = [0;1;0]
3-element Array{Int64,1}:
0
1
0
julia> b = [0;0;1]
3-element Array{Int64,1}:
0
0
1
julia> cross(a,b)
3-element Array{Int64,1}:
1
0
0
```
"""
function cross(a::AbstractVector, b::AbstractVector)
if !(length(a) == length(b) == 3)
throw(DimensionMismatch("cross product is only defined for vectors of length 3"))
end
a1, a2, a3 = a
b1, b2, b3 = b
[a2*b3-a3*b2, a3*b1-a1*b3, a1*b2-a2*b1]
end
"""
triu(M)
Upper triangle of a matrix.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> triu(a)
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
0.0 1.0 1.0 1.0
0.0 0.0 1.0 1.0
0.0 0.0 0.0 1.0
```
"""
triu(M::AbstractMatrix) = triu!(copy(M))
"""
tril(M)
Lower triangle of a matrix.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a)
4×4 Array{Float64,2}:
1.0 0.0 0.0 0.0
1.0 1.0 0.0 0.0
1.0 1.0 1.0 0.0
1.0 1.0 1.0 1.0
```
"""
tril(M::AbstractMatrix) = tril!(copy(M))
"""
triu(M, k::Integer)
Returns the upper triangle of `M` starting from the `k`th superdiagonal.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> triu(a,3)
4×4 Array{Float64,2}:
0.0 0.0 0.0 1.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
julia> triu(a,-3)
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
```
"""
triu(M::AbstractMatrix,k::Integer) = triu!(copy(M),k)
"""
tril(M, k::Integer)
Returns the lower triangle of `M` starting from the `k`th superdiagonal.
# Examples
```jldoctest
julia> a = fill(1.0, (4,4))
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a,3)
4×4 Array{Float64,2}:
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
1.0 1.0 1.0 1.0
julia> tril(a,-3)
4×4 Array{Float64,2}:
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0
1.0 0.0 0.0 0.0
```
"""
tril(M::AbstractMatrix,k::Integer) = tril!(copy(M),k)
"""
triu!(M)
Upper triangle of a matrix, overwriting `M` in the process.
See also [`triu`](@ref).
"""
triu!(M::AbstractMatrix) = triu!(M,0)
"""
tril!(M)
Lower triangle of a matrix, overwriting `M` in the process.
See also [`tril`](@ref).
"""
tril!(M::AbstractMatrix) = tril!(M,0)
diag(A::AbstractVector) = throw(ArgumentError("use diagm instead of diag to construct a diagonal matrix"))
###########################################################################################
# Inner products and norms
# special cases of vecnorm; note that they don't need to handle isempty(x)
function generic_vecnormMinusInf(x)
(v, s) = iterate(x)::Tuple
minabs = norm(v)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
vnorm = norm(v)
minabs = ifelse(isnan(minabs) | (minabs < vnorm), minabs, vnorm)
end
return float(minabs)
end
function generic_vecnormInf(x)
(v, s) = iterate(x)::Tuple
maxabs = norm(v)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
vnorm = norm(v)
maxabs = ifelse(isnan(maxabs) | (maxabs > vnorm), maxabs, vnorm)
end
return float(maxabs)
end
function generic_vecnorm1(x)
(v, s) = iterate(x)::Tuple
av = float(norm(v))
T = typeof(av)
sum::promote_type(Float64, T) = av
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += norm(v)
end
return convert(T, sum)
end
# faster computation of norm(x)^2, avoiding overflow for integers
norm_sqr(x) = norm(x)^2
norm_sqr(x::Number) = abs2(x)
norm_sqr(x::Union{T,Complex{T},Rational{T}}) where {T<:Integer} = abs2(float(x))
function generic_vecnorm2(x)
maxabs = vecnormInf(x)
(maxabs == 0 || isinf(maxabs)) && return maxabs
(v, s) = iterate(x)::Tuple
T = typeof(maxabs)
if isfinite(_length(x)*maxabs*maxabs) && maxabs*maxabs != 0 # Scaling not necessary
sum::promote_type(Float64, T) = norm_sqr(v)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += norm_sqr(v)
end
return convert(T, sqrt(sum))
else
sum = abs2(norm(v)/maxabs)
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += (norm(v)/maxabs)^2
end
return convert(T, maxabs*sqrt(sum))
end
end
# Compute L_p norm ‖x‖ₚ = sum(abs(x).^p)^(1/p)
# (Not technically a "norm" for p < 1.)
function generic_vecnormp(x, p)
(v, s) = iterate(x)::Tuple
if p > 1 || p < -1 # might need to rescale to avoid overflow
maxabs = p > 1 ? vecnormInf(x) : vecnormMinusInf(x)
(maxabs == 0 || isinf(maxabs)) && return maxabs
T = typeof(maxabs)
else
T = typeof(float(norm(v)))
end
spp::promote_type(Float64, T) = p
if -1 <= p <= 1 || (isfinite(_length(x)*maxabs^spp) && maxabs^spp != 0) # scaling not necessary
sum::promote_type(Float64, T) = norm(v)^spp
while true
y = iterate(x, s)
y === nothing && break
(v, s) = y
sum += norm(v)^spp
end
return convert(T, sum^inv(spp))
else # rescaling
sum = (norm(v)/maxabs)^spp
while true
y = iterate(x, s)
y == nothing && break
(v, s) = y
sum += (norm(v)/maxabs)^spp
end
return convert(T, maxabs*sum^inv(spp))
end
end
vecnormMinusInf(x) = generic_vecnormMinusInf(x)
vecnormInf(x) = generic_vecnormInf(x)
vecnorm1(x) = generic_vecnorm1(x)
vecnorm2(x) = generic_vecnorm2(x)
vecnormp(x, p) = generic_vecnormp(x, p)
"""
vecnorm(A, p::Real=2)
For any iterable container `A` (including arrays of any dimension) of numbers (or any
element type for which `norm` is defined), compute the `p`-norm (defaulting to `p=2`) as if
`A` were a vector of the corresponding length.
The `p`-norm is defined as:
```math
\\|A\\|_p = \\left( \\sum_{i=1}^n | a_i | ^p \\right)^{1/p}
```
with ``a_i`` the entries of ``A`` and ``n`` its length.
`p` can assume any numeric value (even though not all values produce a
mathematically valid vector norm). In particular, `vecnorm(A, Inf)` returns the largest value
in `abs(A)`, whereas `vecnorm(A, -Inf)` returns the smallest. If `A` is a matrix and `p=2`,
then this is equivalent to the Frobenius norm.
# Examples
```jldoctest
julia> vecnorm([1 2 3; 4 5 6; 7 8 9])
16.881943016134134
julia> vecnorm([1 2 3 4 5 6 7 8 9])
16.881943016134134
```
"""
function vecnorm(itr, p::Real=2)
isempty(itr) && return float(norm(zero(eltype(itr))))
if p == 2
return vecnorm2(itr)
elseif p == 1
return vecnorm1(itr)
elseif p == Inf
return vecnormInf(itr)
elseif p == 0
return typeof(float(norm(first(itr))))(count(!iszero, itr))
elseif p == -Inf
return vecnormMinusInf(itr)
else
vecnormp(itr,p)
end
end
"""
vecnorm(x::Number, p::Real=2)
For numbers, return ``\\left( |x|^p \\right) ^{1/p}``.
# Examples
```jldoctest
julia> vecnorm(2, 1)
2
julia> vecnorm(-2, 1)
2
julia> vecnorm(2, 2)
2
julia> vecnorm(-2, 2)
2
julia> vecnorm(2, Inf)
2
julia> vecnorm(-2, Inf)
2
```
"""
@inline vecnorm(x::Number, p::Real=2) = p == 0 ? (x==0 ? zero(abs(x)) : oneunit(abs(x))) : abs(x)
function norm1(A::AbstractMatrix{T}) where T
m, n = size(A)
Tnorm = typeof(float(real(zero(T))))
Tsum = promote_type(Float64, Tnorm)
nrm::Tsum = 0
@inbounds begin
for j = 1:n
nrmj::Tsum = 0
for i = 1:m
nrmj += norm(A[i,j])
end
nrm = max(nrm,nrmj)
end
end
return convert(Tnorm, nrm)
end
function norm2(A::AbstractMatrix{T}) where T
m,n = size(A)
if m == 1 || n == 1 return vecnorm2(A) end
Tnorm = typeof(float(real(zero(T))))
(m == 0 || n == 0) ? zero(Tnorm) : convert(Tnorm, svdvals(A)[1])
end
function normInf(A::AbstractMatrix{T}) where T
m,n = size(A)
Tnorm = typeof(float(real(zero(T))))
Tsum = promote_type(Float64, Tnorm)
nrm::Tsum = 0
@inbounds begin
for i = 1:m
nrmi::Tsum = 0
for j = 1:n
nrmi += norm(A[i,j])
end
nrm = max(nrm,nrmi)
end
end
return convert(Tnorm, nrm)
end
"""
norm(A::AbstractArray, p::Real=2)
Compute the `p`-norm of a vector or the operator norm of a matrix `A`,
defaulting to the 2-norm.
norm(A::AbstractVector, p::Real=2)
For vectors, this is equivalent to [`vecnorm`](@ref) and equal to:
```math
\\|A\\|_p = \\left( \\sum_{i=1}^n | a_i | ^p \\right)^{1/p}
```
with ``a_i`` the entries of ``A`` and ``n`` its length.
`p` can assume any numeric value (even though not all values produce a
mathematically valid vector norm). In particular, `norm(A, Inf)` returns the largest value
in `abs(A)`, whereas `norm(A, -Inf)` returns the smallest.
# Examples
```jldoctest
julia> v = [3, -2, 6]
3-element Array{Int64,1}:
3
-2
6
julia> norm(v)
7.0
julia> norm(v, Inf)
6.0
```
"""
norm(x::AbstractVector, p::Real=2) = vecnorm(x, p)
"""
norm(A::AbstractMatrix, p::Real=2)
For matrices, the matrix norm induced by the vector `p`-norm is used, where valid values of
`p` are `1`, `2`, or `Inf`. (Note that for sparse matrices, `p=2` is currently not
implemented.) Use [`vecnorm`](@ref) to compute the Frobenius norm.
When `p=1`, the matrix norm is the maximum absolute column sum of `A`:
```math
\\|A\\|_1 = \\max_{1 ≤ j ≤ n} \\sum_{i=1}^m | a_{ij} |
```
with ``a_{ij}`` the entries of ``A``, and ``m`` and ``n`` its dimensions.
When `p=2`, the matrix norm is the spectral norm, equal to the largest
singular value of `A`.
When `p=Inf`, the matrix norm is the maximum absolute row sum of `A`:
```math
\\|A\\|_\\infty = \\max_{1 ≤ i ≤ m} \\sum _{j=1}^n | a_{ij} |
```
# Examples
```jldoctest
julia> A = [1 -2 -3; 2 3 -1]
2×3 Array{Int64,2}:
1 -2 -3
2 3 -1
julia> norm(A, Inf)
6.0
```
"""
function norm(A::AbstractMatrix, p::Real=2)
if p == 2
return norm2(A)
elseif p == 1
return norm1(A)
elseif p == Inf
return normInf(A)
else
throw(ArgumentError("invalid p-norm p=$p. Valid: 1, 2, Inf"))
end
end
"""
norm(x::Number, p::Real=2)
For numbers, return ``\\left( |x|^p \\right)^{1/p}``.
This is equivalent to [`vecnorm`](@ref).
"""
@inline norm(x::Number, p::Real=2) = vecnorm(x, p)
"""
norm(A::Adjoint{<:Any,<:AbstracVector}, q::Real=2)
norm(A::Transpose{<:Any,<:AbstracVector}, q::Real=2)
For Adjoint/Transpose-wrapped vectors, return the ``q``-norm of `A`, which is
equivalent to the p-norm with value `p = q/(q-1)`. They coincide at `p = q = 2`.
The difference in norm between a vector space and its dual arises to preserve
the relationship between duality and the inner product, and the result is
consistent with the p-norm of `1 × n` matrix.
# Examples
```jldoctest
julia> v = [1; im];
julia> vc = v';
julia> norm(vc, 1)
1.0
julia> norm(v, 1)
2.0
julia> norm(vc, 2)
1.4142135623730951
julia> norm(v, 2)
1.4142135623730951
julia> norm(vc, Inf)
2.0
julia> norm(v, Inf)
1.0
```
"""
norm(v::TransposeAbsVec, q::Real) = q == Inf ? norm(v.parent, 1) : norm(v.parent, q/(q-1))
norm(v::AdjointAbsVec, q::Real) = q == Inf ? norm(conj(v.parent), 1) : norm(conj(v.parent), q/(q-1))
norm(v::AdjointAbsVec) = norm(conj(v.parent))
norm(v::TransposeAbsVec) = norm(v.parent)
function vecdot(x::AbstractArray, y::AbstractArray)
lx = _length(x)
if lx != _length(y)
throw(DimensionMismatch("first array has length $(lx) which does not match the length of the second, $(_length(y))."))
end
if lx == 0
return dot(zero(eltype(x)), zero(eltype(y)))
end
s = zero(dot(first(x), first(y)))
for (Ix, Iy) in zip(eachindex(x), eachindex(y))
@inbounds s += dot(x[Ix], y[Iy])
end
s
end
"""
vecdot(x, y)
For any iterable containers `x` and `y` (including arrays of any dimension) of numbers (or
any element type for which `dot` is defined), compute the Euclidean dot product (the sum of
`dot(x[i],y[i])`) as if they were vectors.
# Examples
```jldoctest
julia> vecdot(1:5, 2:6)
70
julia> x = fill(2., (5,5));
julia> y = fill(3., (5,5));
julia> vecdot(x, y)
150.0
```
"""
function vecdot(x, y) # arbitrary iterables
ix = iterate(x)
iy = iterate(y)
if ix === nothing
if iy !== nothing
throw(DimensionMismatch("x and y are of different lengths!"))
end
return dot(zero(eltype(x)), zero(eltype(y)))
end
if iy === nothing
throw(DimensionMismatch("x and y are of different lengths!"))
end
(vx, xs) = ix
(vy, ys) = iy
s = dot(vx, vy)
while true
ix = iterate(x, xs)
iy = iterate(y, ys)
if (ix == nothing) || (iy == nothing)
break
end
(vx, xs), (vy, ys) = ix, iy
s += dot(vx, vy)
end
if !(iy == nothing && ix == nothing)
throw(DimensionMismatch("x and y are of different lengths!"))
end
return s
end
vecdot(x::Number, y::Number) = conj(x) * y
dot(x::Number, y::Number) = vecdot(x, y)
"""
dot(x, y)
⋅(x,y)
Compute the dot product between two vectors. For complex vectors, the first vector is conjugated.
When the vectors have equal lengths, calling `dot` is semantically equivalent to `sum(vx'vy for (vx,vy) in zip(x, y))`.
# Examples
```jldoctest
julia> dot([1; 1], [2; 3])
5
julia> dot([im; im], [1; 1])
0 - 2im
```
"""
function dot(x::AbstractVector, y::AbstractVector)
if length(x) != length(y)
throw(DimensionMismatch("dot product arguments have lengths $(length(x)) and $(length(y))"))
end
ix = iterate(x)
if ix === nothing
# we only need to check the first vector, since equal lengths have been asserted
return zero(eltype(x))'zero(eltype(y))
end
iy = iterate(y)
s = ix[1]'iy[1]
ix, iy = iterate(x, ix[2]), iterate(y, iy[2])
while ix != nothing
s += ix[1]'iy[1]
ix = iterate(x, ix[2])
iy = iterate(y, iy[2])
end
return s
end
# Call optimized BLAS methods for vectors of numbers
dot(x::AbstractVector{<:Number}, y::AbstractVector{<:Number}) = vecdot(x, y)
###########################################################################################
"""
rank(A[, tol::Real])
Compute the rank of a matrix by counting how many singular
values of `A` have magnitude greater than `tol*σ₁` where `σ₁` is
`A`'s largest singular values. By default, the value of `tol` is the smallest
dimension of `A` multiplied by the [`eps`](@ref)
of the [`eltype`](@ref) of `A`.
# Examples
```jldoctest
julia> rank(Matrix(I, 3, 3))
3
julia> rank(diagm(0 => [1, 0, 2]))
2
julia> rank(diagm(0 => [1, 0.001, 2]), 0.1)
2
julia> rank(diagm(0 => [1, 0.001, 2]), 0.00001)
3
```
"""
function rank(A::AbstractMatrix, tol::Real = min(size(A)...)*eps(real(float(one(eltype(A))))))
s = svdvals(A)
count(x -> x > tol*s[1], s)
end
rank(x::Number) = x == 0 ? 0 : 1
"""
tr(M)
Matrix trace. Sums the diagonal elements of `M`.
# Examples
```jldoctest
julia> A = [1 2; 3 4]
2×2 Array{Int64,2}:
1 2
3 4
julia> tr(A)
5
```
"""
function tr(A::AbstractMatrix)
checksquare(A)
sum(diag(A))
end
tr(x::Number) = x
#kron(a::AbstractVector, b::AbstractVector)
#kron(a::AbstractMatrix{T}, b::AbstractMatrix{S}) where {T,S}
#det(a::AbstractMatrix)
"""
inv(M)
Matrix inverse. Computes matrix `N` such that
`M * N = I`, where `I` is the identity matrix.
Computed by solving the left-division
`N = M \\ I`.
# Examples
```jldoctest
julia> M = [2 5; 1 3]
2×2 Array{Int64,2}:
2 5
1 3
julia> N = inv(M)
2×2 Array{Float64,2}:
3.0 -5.0
-1.0 2.0
julia> M*N == N*M == Matrix(I, 2, 2)
true
```
"""
function inv(A::AbstractMatrix{T}) where T
n = checksquare(A)
S = typeof(zero(T)/one(T)) # dimensionful
S0 = typeof(zero(T)/oneunit(T)) # dimensionless
dest = Matrix{S0}(I, n, n)
ldiv!(factorize(convert(AbstractMatrix{S}, A)), dest)
end
pinv(v::AbstractVector{T}, tol::Real = real(zero(T))) where {T<:Real} = _vectorpinv(transpose, v, tol)
pinv(v::AbstractVector{T}, tol::Real = real(zero(T))) where {T<:Complex} = _vectorpinv(adjoint, v, tol)
pinv(v::AbstractVector{T}, tol::Real = real(zero(T))) where {T} = _vectorpinv(adjoint, v, tol)
function _vectorpinv(dualfn::Tf, v::AbstractVector{Tv}, tol) where {Tv,Tf}
res = dualfn(similar(v, typeof(zero(Tv) / (abs2(one(Tv)) + abs2(one(Tv))))))
den = sum(abs2, v)
# as tol is the threshold relative to the maximum singular value, for a vector with
# single singular value σ=√den, σ ≦ tol*σ is equivalent to den=0 ∨ tol≥1
if iszero(den) || tol >= one(tol)
fill!(res, zero(eltype(res)))
else
res .= dualfn(v) ./ den
end
return res
end
# this method is just an optimization: literal negative powers of A are
# already turned by literal_pow into powers of inv(A), but for A^-1 this
# would turn into inv(A)^1 = copy(inv(A)), which makes an extra copy.
@inline Base.literal_pow(::typeof(^), A::AbstractMatrix, ::Val{-1}) = inv(A)
"""
\\(A, B)
Matrix division using a polyalgorithm. For input matrices `A` and `B`, the result `X` is
such that `A*X == B` when `A` is square. The solver that is used depends upon the structure
of `A`. If `A` is upper or lower triangular (or diagonal), no factorization of `A` is
required and the system is solved with either forward or backward substitution.
For non-triangular square matrices, an LU factorization is used.
For rectangular `A` the result is the minimum-norm least squares solution computed by a
pivoted QR factorization of `A` and a rank estimate of `A` based on the R factor.
When `A` is sparse, a similar polyalgorithm is used. For indefinite matrices, the `LDLt`
factorization does not use pivoting during the numerical factorization and therefore the
procedure can fail even for invertible matrices.
# Examples
```jldoctest
julia> A = [1 0; 1 -2]; B = [32; -4];
julia> X = A \\ B
2-element Array{Float64,1}:
32.0
18.0
julia> A * X == B
true
```
"""
function (\)(A::AbstractMatrix, B::AbstractVecOrMat)
m, n = size(A)
if m == n
if istril(A)
if istriu(A)
return Diagonal(A) \ B
else
return LowerTriangular(A) \ B
end
end
if istriu(A)
return UpperTriangular(A) \ B
end
return lu(A) \ B
end
return qr(A,Val(true)) \ B
end
(\)(a::AbstractVector, b::AbstractArray) = pinv(a) * b
(/)(A::AbstractVecOrMat, B::AbstractVecOrMat) = copy(adjoint(adjoint(B) \ adjoint(A)))
# \(A::StridedMatrix,x::Number) = inv(A)*x Should be added at some point when the old elementwise version has been deprecated long enough
# /(x::Number,A::StridedMatrix) = x*inv(A)
/(x::Number, v::AbstractVector) = x*pinv(v)
cond(x::Number) = x == 0 ? Inf : 1.0
cond(x::Number, p) = cond(x)
#Skeel condition numbers
condskeel(A::AbstractMatrix, p::Real=Inf) = norm(abs.(inv(A))*abs.(A), p)
"""
condskeel(M, [x, p::Real=Inf])
```math
\\kappa_S(M, p) = \\left\\Vert \\left\\vert M \\right\\vert \\left\\vert M^{-1} \\right\\vert \\right\\Vert_p \\\\
\\kappa_S(M, x, p) = \\left\\Vert \\left\\vert M \\right\\vert \\left\\vert M^{-1} \\right\\vert \\left\\vert x \\right\\vert \\right\\Vert_p
```
Skeel condition number ``\\kappa_S`` of the matrix `M`, optionally with respect to the
vector `x`, as computed using the operator `p`-norm. ``\\left\\vert M \\right\\vert``
denotes the matrix of (entry wise) absolute values of ``M``;
``\\left\\vert M \\right\\vert_{ij} = \\left\\vert M_{ij} \\right\\vert``.
Valid values for `p` are `1`, `2` and `Inf` (default).
This quantity is also known in the literature as the Bauer condition number, relative
condition number, or componentwise relative condition number.
"""
condskeel(A::AbstractMatrix, x::AbstractVector, p::Real=Inf) = norm(abs.(inv(A))*(abs.(A)*abs.(x)), p)
issymmetric(A::AbstractMatrix{<:Real}) = ishermitian(A)
"""
issymmetric(A) -> Bool
Test whether a matrix is symmetric.
# Examples
```jldoctest
julia> a = [1 2; 2 -1]
2×2 Array{Int64,2}:
1 2
2 -1
julia> issymmetric(a)
true
julia> b = [1 im; -im 1]
2×2 Array{Complex{Int64},2}:
1+0im 0+1im
0-1im 1+0im
julia> issymmetric(b)
false
```
"""
function issymmetric(A::AbstractMatrix)
indsm, indsn = axes(A)
if indsm != indsn
return false
end
for i = first(indsn):last(indsn), j = (i):last(indsn)
if A[i,j] != transpose(A[j,i])
return false
end
end
return true
end
issymmetric(x::Number) = x == x
"""
ishermitian(A) -> Bool
Test whether a matrix is Hermitian.
# Examples
```jldoctest
julia> a = [1 2; 2 -1]
2×2 Array{Int64,2}:
1 2
2 -1
julia> ishermitian(a)
true
julia> b = [1 im; -im 1]
2×2 Array{Complex{Int64},2}:
1+0im 0+1im
0-1im 1+0im
julia> ishermitian(b)
true
```
"""
function ishermitian(A::AbstractMatrix)
indsm, indsn = axes(A)
if indsm != indsn
return false
end
for i = indsn, j = i:last(indsn)
if A[i,j] != adjoint(A[j,i])
return false
end
end
return true
end
ishermitian(x::Number) = (x == conj(x))
"""
istriu(A::AbstractMatrix, k::Integer = 0) -> Bool
Test whether `A` is upper triangular starting from the `k`th superdiagonal.
# Examples
```jldoctest
julia> a = [1 2; 2 -1]
2×2 Array{Int64,2}:
1 2
2 -1
julia> istriu(a)
false
julia> istriu(a, -1)
true
julia> b = [1 im; 0 -1]
2×2 Array{Complex{Int64},2}: