我尝试通过将t = range(0,stop=2*pi,length=101)
乘以矩阵[1, 0]
来创建一个矩阵数组,如下所示
A = t .* [1 ,0]
但这会产生错误ERROR: LoadError: DimensionMismatch("arrays could not be broadcast to a common size")
。我希望将t
的每个标量或元素与向量[1 , 0]
的元素进行元素乘法(就t
而言),本质上是执行元素的标量矩阵乘积。
我这样做的原因是因为我希望以后能够将A
中找到的每个列向量与另一个常量矩阵M
相乘。在Julia v1.1中如何做到这一点?
发布于 2019-08-28 21:04:59
你必须将你不想被广播的元素包装在一个容器中。下面是一个标准的实现方法(为了让示例更清晰,我将length
kwarg减少为3
):
julia> t = range(0,stop=2*pi,length=3)
0.0:3.141592653589793:6.283185307179586
julia> A = t .* Ref([1 ,0])
3-element Array{Array{Float64,1},1}:
[0.0, 0.0]
[3.141592653589793, 0.0]
[6.283185307179586, 0.0]
julia> Ref([1 2; 3 4]) .* A
3-element Array{Array{Float64,1},1}:
[0.0, 0.0]
[3.141592653589793, 9.42477796076938]
[6.283185307179586, 18.84955592153876]
除了Ref
容器,您还可以使用1元素元组或1元素向量作为包装器:
julia> t .* ([1 ,0],)
3-element Array{Array{Float64,1},1}:
[0.0, 0.0]
[3.141592653589793, 0.0]
[6.283185307179586, 0.0]
julia> t .* [[1 ,0]]
3-element Array{Array{Float64,1},1}:
[0.0, 0.0]
[3.141592653589793, 0.0]
[6.283185307179586, 0.0]
应该首选Ref
的原因是它是0维的,因此它是这三种方法中最中立的(即以最小的方式影响输出-保留其他参数的广播风格)。下面是一些示例:
julia> f1(x) = x .* (2, )
f1 (generic function with 1 method)
julia> f2(x) = x .* [2]
f2 (generic function with 1 method)
julia> f3(x) = x .* Ref(2)
f3 (generic function with 1 method)
julia> f1(1)
(2,)
julia> f2(1)
1-element Array{Int64,1}:
2
julia> f3(1)
2
julia> f1((1,2))
(2, 4)
julia> f2((1,2))
2-element Array{Int64,1}:
2
4
julia> f3((1,2))
(2, 4)
https://stackoverflow.com/questions/57692430
复制相似问题