Generate an array of matrices

Hi I want to generate an array A in which each element is a 2\times 2 matrix. And I want to initialize this array such that each element is [1/2 0; 0 1/2]. Later I want to replace some element by different matrices like A[i] = [a b; c d] and I want to be able to get each element, ,like temp = A[j] for further computation. What is the efficient way to do this? Thanks.

Edit: No, fill fills the array with addresses to the same matrix, my bad. Here’s how to do it:

A = [[0.5 0; 0 0.5] for i=1:10]
A[2] .= [1 1;1 0]
B = A[5]
1 Like

Yes this works. Thank you!

For 2x2 matrices I would use StaticArrays:

using StaticArrays 
A = fill(SA[0.5 0.0; 0.0 0.5], 10)
A[2] = SA[1.0 1.0;1.0 0.0] 

SArrays are immutable, so you cannot use dot-assignment in the last line, but you can use fill.

This will be much more efficient than regular arrays.

4 Likes

Sorry, I can’t see why fill doesn’t work. I tried the previous version A = fill([1/2 0; 0 1/2],10) and it gives me an array of matrices. I can also change the elements like A[1] = [1 2;3 4]. Could you please explain why fill fails? Thank you.

The problem is that every element of the vector A refers to the same object.


julia> A = fill([1/2 0; 0 1/2], 4)
4-element Vector{Matrix{Float64}}:
 [0.5 0.0; 0.0 0.5]
 [0.5 0.0; 0.0 0.5]
 [0.5 0.0; 0.0 0.5]
 [0.5 0.0; 0.0 0.5]

julia> A[1][1,1] = 123
123

julia> A
4-element Vector{Matrix{Float64}}:
 [123.0 0.0; 0.0 0.5]
 [123.0 0.0; 0.0 0.5]
 [123.0 0.0; 0.0 0.5]
 [123.0 0.0; 0.0 0.5]

Basically you have the same matrix several times! I don’t think you want that.

Oh I see. Thank you!

I second @DNF’s suggestion. The fill issue just described is not a problem with SMatrix.

Hi guys. I have one more question. Suppose I need to replace one element of the array to be a complex matrix like A[i] = [1+im 0;0 1-im], then I need to use [1/2+0*im 0; 0 1/2+0*im] when I initialize the array, right?

Just to be clear for those who don’t know, fill has the exact same semantics in both cases, it’s just that if the array is immutable (like a StaticArray) then there’s no difference between n references to the same object and a n distinct objects. But if you are doing the same operations with both types (without errors), you should get the same results. Maybe that’s pedantic but to me it feels confusing to describe the behavior as depending on the mutability of the object. That said, I agree fill is often more useful when there’s no danger of mutating, which you get with StaticArrays.

Yeah, you need to do that, or you could specify the type when creating the matrices directly, like

A = [Complex{Float64}[0.5 0; 0 0.5] for i=1:10]

Got it. Thanks

And Now for Something Completely Different :wink:
Generate a normal array and divide it into blocks
You can index with the normal index, or blockwise
ie.


.