Chris Ze Third
Chris Ze Third

Reputation: 359

Can't add array to Matlab dictionary

I'm trying to add an array to a dictionary in Matlab.

In Python it's very simple, just make a dictionary and for a key assign an array, but in Matlab I get this error:

Error using () Dimensions of the key and value must be compatible, or the value must be scalar.

Basically all I want to do is:

d = dictionary
arr = [1 0.2 7 0.3]
d('key') = arr

But it doesn't work and I don't understand what I am supposed to do.

Upvotes: 2

Views: 1578

Answers (2)

Chris Ze Third
Chris Ze Third

Reputation: 359

% create an array
array = [1, 2, 3];

% create a dictionary
dictionary = containers.Map;

% add the array to the dictionary
dictionary('array') = array;

I found this alternative by accident looking for a matlab reddit or discord server. And I basically found an amazing AI assistant website https://gistlib.com/matlab/add-array-to-dictionary-in-matlab.

So this solves this mystery.

Upvotes: 0

Cris Luengo
Cris Luengo

Reputation: 60574

According to the documentation:

Individual elements of values must be scalars of the same data type. If values need to be heterogeneous or nonscalar, use a cell array.

So, to store an array under a key, use:

d("key") = {arr};

Upvotes: 3

Related Questions