I have three arrays of arrays like this:
catLabels = [catA, catB, catC]
binaryLabels = [binA, binB, binC]
trueLabels = []
trueLabels.extend(repeat(y_true_categories, len(binaryLabels)))
def binaryConversion(trueLabel, evalLabel, binaryLabel):
for true,eval, binary in zip(trueLabel, evalLabel, binaryLabel):
if eval == true:
binary.append(1)
else:
binary.append(0)
for x,y,z in zip(trueLabels,catLabels,binaryLabels):
binaryConversion(x, y, z)
Each of the values in catLabels and binLabels is an array. binLabels contain an array of empty arrays, each of which I want to fill in 1s and 0s lets say for example catA = [A B C A B D] and binA = []. trueLabels contains multiple arrays each of which are the same (y_true_categories, i.e. my true categorical labels [A C C B B D]. In this case, my binaryConversion function should fill in [1 0 1 0 1 1] for the array binA.
For some reason my current function is not achieving this and leaves each of bin A, binB, binC empty.
What am I doing wrong?
I have figured out the answer. The inner zip statement will not work because I start with empty binary labels, and zip only works when all the arrays you are zipping are of the same length. So I removed the binaryLabel from the zip function within binaryConversion(trueLabel, evalLabel, binaryLabel) and appended to each binaryLabel empty binary array inside the loop. In addition, I was appending 1s and 0s to the element-wise binary, instead of the actual empty array binaryLabel.
New code:
def binaryConversion(trueLabel, evalLabel, emptyBinaryArray):
for true,eval in zip(trueLabel, evalLabel):
if eval == true:
emptyBinaryArray.append(1)
else:
emptyBinaryArray.append(0)
for trueLabels,predictionLabels,emptyBinaryArray in zip(trueLabels,catLabels,binaryLabels):
binaryConversion(trueLabels, predictionLabels, emptyBinaryArray)
Related
Here I have this where import data as arrays then, operates on those arrays with a function
import numpy as np
n1 = an array of 999 numbers
mass1= an array of 999 numbers
x1= an array of 999 numbers
y1=an array of 999 numbers
z1=an array of 999 numbers
dt=.0001
npoints=len(n1)
xn=0
step=1
for timedt in xrange(0,npoints-1):
step=step
for l in xrange(0,npoints-1):
xn=xn
f=x1,y1,z1[xn]+x1,y1,z1[step]
xn=xn+1
step=step+1
print f
However, when I print out f, I just get a huge list set of numbers in the format
.....
-9.622302989262075e-07
0.00016890654402323984
2.261014843829707e-05
-0.00011706036947314393
-7.791712660429376e-05
1.0156155973842854e-05
0.00019244252361596046
-0.00019202953520118445
0.04082168851673397
-0.001675463103312094
-1.4584179607758451e-05
3.788355464183264
3.99516377369456e-05
But I want to make these numbers be one array. In additon if I print f outside of that loop, I only get the last number.
3.99516377369456e-05
But I want to be able to print all of them outside of the loop as an array.
np.asarray
doesn't work.
The easiest way would possibly be:
f_array = []
for ...:
...
for ...:
f = ...
f_array.append(f)
f_array = np.array(f_array)
I have a function that uses strfind in a cellfun call to find which string items in a cell array match a specified string. For example:
cellfun( #(x) strfind( x , 'openmask'), fileNames, 'uniformoutput', false)
The original cell matrix is like this:
fileNames = {'sub11att-openmask.txt', 'sub13det-masking', ...};
The result for this looks like this:
[10] [] [10] [] [9] []
I am trying to find a function that will convert this to:
10 0 10 0 9 0
Using cell2mat I get:
10 10 9
So I have to use this currently:
x(cellfun('isempty', x))={0};
cell2mat(x);
Is there a function that is cleaner than this (i.e. a one-liner solution)?
Thanks.
This works even if there are several occurrences of the sought string. It finds the first such occurrence if there's any, or gives 0 otherwise:
result = cellfun(#(x) sum(min(strfind(x, 'openmask'))), fileNames);
The code uses min to keep the first occurrence. This will give either a number or []. Then sum transforms [] into 0.
If you prefer to keep the last occurrence, change min to max or use Sardar Usama's suggestion:
result = cellfun(#(x) max([0 strfind(x, 'openmask')]), fileNames);
For a new variable y:
y(~cellfun('isempty', x)) = cell2mat(x);
It will break if a cell has more than one element tough.
So my main objective is to take a matrix of form
matrix = [a, 1; b, 2; c, 3]
and a list of identifiers in matrix[:,1]
list = [a; c]
and generate a new matrix
new_matrix = [a, 1;c, 3]
My problem is I need to import the data that would be used in 'matrix' from a tab-delimited text file. To get this data into Matlab I use the code:
matrix_open = fopen(fn_matrix, 'r');
matrix = textscan(matrix_open, '%c %d', 'Delimiter', '\t');
which outputs a cell array of two 3x1 arrays. I want to get this into one 3x2 matrix where the first column is a character, and the second column an integer (these data formats will be different in my implementation).
So far I've tried the code:
matrix_1 = cell2mat(matrix(1,1));
matrix_2 = cell2mat(matrix(1,2));
matrix = horzcat(matrix_1, matrix_2)
but this is returning a 3x2 matrix where the second column is empty.
If I just use
cell2mat(matrix)
it says it can't do it because of the different data formats.
Thanks!
This is the help of matlab for the cell2mat function:
cell2mat Convert the contents of a cell array into a single matrix.
M = cell2mat(C) converts a multidimensional cell array with contents of
the same data type into a single matrix. The contents of C must be able
to concatenate into a hyperrectangle. Moreover, for each pair of
neighboring cells, the dimensions of the cell's contents must match,
excluding the dimension in which the cells are neighbors. This constraint
must hold true for neighboring cells along all of the cell array's
dimensions.
From what I understand the contents you want to put in a matrix should be of the same type otherwise why do you want a matrix? you could simply create a new cell array.
It's not possible to have a normal matrix with characters and numbers. That's why cell2mat won't work here. But you can store different datatypes in a cell-array. Use cellstr for the strings/characters and num2cell for the integers to convert the contents of matrix. If you have other datatypes, use an appropriate function for this step. Then assign them to the columns of an empty cell-array.
Here is the code:
fn_matrix = 'data.txt';
matrix_open = fopen(fn_matrix, 'r');
matrix = textscan(matrix_open, '%c %d', 'Delimiter', '\t');
X = cell(size(matrix{1},1),2);
X(:,1) = cellstr(matrix{1});
X(:,2) = num2cell(matrix{2});
The result:
X =
'a' [1]
'b' [2]
'c' [3]
Now we can do the second part of the question. Extracting the entries where the letter matches with one of the list. Therefore you can use ismember and logical indexing like this:
list = ['a'; 'c'];
sel = ismember(X(:,1),list);
Y(:,1) = X(sel,1);
Y(:,2) = X(sel,2);
The result here:
Y =
'a' [1]
'c' [3]
I have the following string A B C D E F G H I J. I want to make an array out of it, so I use this
my #string = split/(\W)/, $text;
It works ok, and I get an array of 20 lines looking like this:
A
B
C
D
...
Now, I want to split this array in a given number of pieces (let's say 4 in this case), thus resulting I imagine in 4 smaller arrays of 5 lines each, looking like this #1 = A, ,B, ,C , #2 = ,D, ,E,, #3 = F, ,G, ,H and #4 = ,I, ,J,.
Finally, I want to interleave these 4 arrays in order to get an output array in which I first have the first line of each array, the the second line of each array, and so on... the final thing looking like this :
A
F
D
I
B
G
E
J
C
H
How to achieve this?
To make a slice of an array in Perl:
my #oldArray = (a, ,b, ,c, ,d, ,e, ,f, ,g, h, ,i, ,j, );
my #newArray1 = #oldArray[elemIndex1,elemIndex2,elemIndexN];
OR
my #newArray1 = #oldArray[firstElemIndex..lastElemIndex]
Where elemIndex is the index of the element you want in the newArray array.
firstElemIndex..lastElemIndex is used when you want consecutive indexes to be in the sliced array.
To add elements at the end of an array:
push(#interleavedArray,$newArray1[elemIndex]);
Where $newArray1[elemIndex] is the element from #newArray1 you want to add to #interleavedArray
To add elements in order:
Just do a for loop:
for my $index (0..3){
push(#interleavedArray,$newArray1[$index]);
push(#interleavedArray,$newArray2[$index]);
push(#interleavedArray,$newArray3[$index]);
push(#interleavedArray,$newArray4[$index]);
}
I am a little confused about the usage of cells and arrays in MATLAB and would like some clarification on a few points. Here are my observations:
An array can dynamically adjust its own memory to allow for a dynamic number of elements, while cells seem to not act in the same way:
a=[]; a=[a 1]; b={}; b={b 1};
Several elements can be retrieved from cells, but it doesn't seem like they can be from arrays:
a={'1' '2'}; figure; plot(...); hold on; plot(...); legend(a{1:2});
b=['1' '2']; figure; plot(...); hold on; plot(...); legend(b(1:2));
%# b(1:2) is an array, not its elements, so it is wrong with legend.
Are these correct? What are some other different usages between cells and array?
Cell arrays can be a little tricky since you can use the [], (), and {} syntaxes in various ways for creating, concatenating, and indexing them, although they each do different things. Addressing your two points:
To grow a cell array, you can use one of the following syntaxes:
b = [b {1}]; % Make a cell with 1 in it, and append it to the existing
% cell array b using []
b = {b{:} 1}; % Get the contents of the cell array as a comma-separated
% list, then regroup them into a cell array along with a
% new value 1
b{end+1} = 1; % Append a new cell to the end of b using {}
b(end+1) = {1}; % Append a new cell to the end of b using ()
When you index a cell array with (), it returns a subset of cells in a cell array. When you index a cell array with {}, it returns a comma-separated list of the cell contents. For example:
b = {1 2 3 4 5}; % A 1-by-5 cell array
c = b(2:4); % A 1-by-3 cell array, equivalent to {2 3 4}
d = [b{2:4}]; % A 1-by-3 numeric array, equivalent to [2 3 4]
For d, the {} syntax extracts the contents of cells 2, 3, and 4 as a comma-separated list, then uses [] to collect these values into a numeric array. Therefore, b{2:4} is equivalent to writing b{2}, b{3}, b{4}, or 2, 3, 4.
With respect to your call to legend, the syntax legend(a{1:2}) is equivalent to legend(a{1}, a{2}), or legend('1', '2'). Thus two arguments (two separate characters) are passed to legend. The syntax legend(b(1:2)) passes a single argument, which is a 1-by-2 string '12'.
Every cell array is an array! From this answer:
[] is an array-related operator. An array can be of any type - array of numbers, char array (string), struct array or cell array. All elements in an array must be of the same type!
Example: [1,2,3,4]
{} is a type. Imagine you want to put items of different type into an array - a number and a string. This is possible with a trick - first put each item into a container {} and then make an array with these containers - cell array.
Example: [{1},{'Hallo'}] with shorthand notation {1, 'Hallo'}