I created a cell Array like this
A{1} = {'aa','b','d','aa'};
A{2} = {'c','d','aa'};
A{3} = {'bb','aa','bb','aa'};
now I wanna find the unique words
b=cell2mat(A)
unique(b)
but I get this Error: Error using cell2mat (line 52) Cannot support cell arrays containing cell arrays or objects.
I'm fairly new to matlab. Am I doing something wrong here?
A{1} = {'aa','b','d','aa'};
A{2} = {'c','d','aa'};
A{3} = {'bb','aa','bb','aa'};
unique([A{:}])
There you go. The {:}, (:) and [] operators are very useful in MATLAB. Get comfortable using them.
Related
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.
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};
% 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.
I have been trying to randomize the values in an ordered array (ex:[0,1,2,3]) in Godot. There is supposed to be a shuffle() method for arrays, but it seems to be broken and always returns "null". I have found a workaround that uses a Fisher-Yates shuffle, but the resulting array is considered "unsorted" by the engine, and therefore when I try to use methods such as bsearch() to find a value by it's position, the results are unreliable at best.
My solution was to create a dictionary, comprised of an array containing the random values I have obtained, merged with a second array of equal length with (sorted) numbers (in numerical order) which I can then use as keys to access specific array positions when needed.
Question made simple...
In GDScript, how would you take 2 arrays..
ex: ARRAY1 = [0,1,2,3]
ARRAY2 = [a,b,c,d]
..and merge them to form a dictionary that looks like this:
MergedDictionary = {0:a, 1:b, 2:c, 3:d}
Any help would be greatly appreciated.
Godot does not support "zip" methodology for merging arrays such as Python does, so I am stuck merging them manually. However... there is little to no documentation about how to do this in GDScript, despite my many hours of searching.
Try this:
var a = [1, 2, 3]
var b = ["a", "b", "c"]
var c = {}
if a.size() == b.size():
var i = 0
for element in a:
c[element] = b[i]
i += 1
print("Dictionary c: ", c)
If you want to add elements to a dictionary, you can assign values to the keys like existing keys.
I am getting "ValueError: setting an array element with a sequence." error when I am trying to run my random forest classifier on a heterogenous data--the text data is been fed to word2vec model and I extracted one dimensional numpy array by taking mean of the word2vec vectors for each word in the text row.
Here is the sample of the data am working with:
col-A col-B ..... col-z
100 230 ...... [0.016612869501113892, -0.04279713928699493, .....]
where col-z is the numpy array with fixed size of 300 in each row.
Following is the code for calculating mean the word2vec vectors and creating numpy arrays:
` final_data = []
for i, row in df.iterrows():
text_vectorized = []
text = row['col-z']
for word in text:
try:
text_vectorized.append(list(w2v_model[word]))
except Exception as e:
pass
try:
text_vectorized = np.asarray(text_vectorized, dtype='object')
text_vectorized_mean = list(np.mean(text_vectorized, axis=0))
except Exception as e:
text_vectorized_mean = list(np.zeros(100))
pass
try:
len(text_vectorized_mean)
except:
text_vectorized_mean = list(np.zeros(100))
temp_row = np.asarray(text_vectorized_mean, dtype='object')
final_data.append(temp_row)
text_array = np.asarray(final_data, dtype='object')`
After this, I convert text_array to pandas dataframe and concatenate it with my original dataframe with other numeric columns. But as soon as I try to feed this data into a classifier, it gives me the above error at this line:
--> array = np.array(array, dtype=dtype, order=order, copy=copy)
Why am I getting this error?
You are trying to create an array from a mixed list containing both numeric values and an another list. Try to flatten the array first using .ravel()
For example,
text_array = np.asarray(final_data.ravel(), dtype='object')
data = {};
data(1) = 'hello';
gives this error Conversion to cell from char is not possible.
my strings are created inside a loop and they are of various lengths. How do I store them in a cell array or list?
I believe that the syntax you want is the following:
data = {};
data{1} = 'hello';
Use curly braces to refer to the contents of a cell:
data{1} = 'hello'; %// assign a string as contents of the cell
The notation data(1) refers to the cell itself, not to its contents. So you could also use (but it's unnecessarily cumbersome here):
data(1) = {'hello'}; %// assign a cell to a cell
More information about indexing into cell arrays can be found here.
my program in R creates an n-dimensional array.
PVALUES = array(0, dim=dimensions)
where dimensions = c(x,y,z, ... )
The dimensions will depend on a particular input. So, I want to create a general-purpose code that will:
Store a particular element in the array
Read a particular element from the array
From reading this site I learned how to do #2 - read an element from the array
ll=list(x,y,z, ...)
element_xyz = do.call(`[`, c(list(PVALUES), ll))
Please help me solving #1, that is storing an element to the n-dimensional array.
Let me rephrase my question
Suppose I have a 4-dimensional array. I can store a value and read a value from this array:
PVALUES[1,1,1,1] = 43 #set a value
data = PVALUES[1,1,1,1] #use a value
How can I perform the same operations using a function of a vector of indexes:
indexes = c(1,1,1,1)
set(PVALUES, indexes) = 43
data = get(PVALUES, indexes) ?
Thank you
Thanks for helpful response.
I will use the following solution:
PVALUES = array(0, dim=dimensions) #Create an n-dimensional array
dimensions = c(x,y,z,...,n)
Set a value to PVALUES[x,y,z,...,n]:
y=c(x,y,z,...,n)
PVALUES[t(y)]=26
Reading a value from PVALUES[x,y,z,...,n]:
y=c(x,y,z,...,n)
data=PVALUES[t(y)]
The indexing of arrays can be done with matrices having the same number of columns as there are dimensions:
# Assignment with "[<-"
newvals <- matrix( c( x,y,z,vals), ncol=4)
PVALUES[ newvals[ ,-4] ] <- vals
# Reading values with "["
PVALUES[ newvals[ ,-4] ]