How to assign Matrix with dimensions (1,1) to a scalar

Hello I’m quite new to Julia and coming from MATLAB and Python and I have some trouble with operations that should be quite common but I haven’t found any workaround/solution in the usual places (Manual, Github and here).

The problem is:
I cannot assign the result of a calculation to array at a specific index. The issue is that the type of the result is a Matrix with dimensions (1,1) which is cannot automatically converted to a scalar (why not?)

Example to reproduce:

A = rand(2,2)
B = rand(2,1)
C = rand(1,2)
r = C * A * B
y_ = zeros(10,1)
y_[1] = r

this results in:

MethodError: Cannot `convert` an object of type Array{Float64,2} to an object of type Float64

I know that I could just index r[1] but this also seems overly complicated.
Are there any better solutions to this?
Is it possible to overwrite e.g. convert()?

1 Like

Probably only is the best. That also assures that there is indeed only one element.

Is it possible to overwrite e.g. convert() ?

No, don’t do that. This will probably break things as other code, in Julia itself or in packages will rely on convert working as advertised (this is called type piracy). Only add methods to convert for types which you defined.

3 Likes

You can use r[] (no indices, just the brackets).

The better answer is that you should be using Vectors instead of 1 column matrices. Specifically, this should be

A = rand(2,2) #matrix
B = rand(2) #vector
C = rand(2)' #row vector
r = C * A * B #scalar
y_ = zeros(10,1)
y_[1] = r
8 Likes

Hmm, only() looks interesting thanks

So just to make sure I’m not missing something: In Julia a scalar are not equivalent and cannot be automatically casted to a vector/matrix with one element?

hmm that’s good to know thanks
(but it’s the same workaround like [1] I was trying to avoid)

Yes. They are two completely different things. But as @Oscar_Smith pointed our above, if you use the “right” types for the rows and columns the result is a scalar.

Yes that’s true, unfortunately it’s not always possible to constrain/control the types in that way. This example e.g. is derived from using ControlSystems package and there the system object automatically uses matrices.

Looking at the documentation, it appears that you can use Vectors (in fact, most of the docs do)

1 Like

Hmm, ok makes sense from a programming point of view (not mathematically though in my opinion)

Anyway thank you all for the quick and helpful responses!