Home > Software design >  Can't add array to Matlab dictionary
Can't add array to Matlab dictionary

Time:11-15

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.

CodePudding user response:

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};

CodePudding user response:

% 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.

  • Related