I am currently using MatLab R2014a
I have one array and one cell:
MyArray = ['AA1', 'AA2', 'AB1', 'AB2', 'Acc1', 'Acc2'];
MyCell = {'Name1AA1', 'Name2AA1', 'Name3Acc2', 'Name4AB2', 'Name5AD1};
MyArray consists of code names that are repeatable throughout MyCell.
I would like to check if any of the strings in MyArray are in MyCell and if it is, save the name to a new cell.
For now I have:
NewCell = {};
for i = 1:length(MyCell)
for j = 1:length(MyArray)
Find = strfind(MyCell(i), MyArray)
if ~isempty(Find)
NewCell = {NewCell; MyCell(j)}
end
end
end
However, when I use strfind I get this error message:
Undefined function 'strfind' for input arguments of type 'char'
If I use strcmp instead of strfind, I get an array of everything in MyCell repeated by the number of elements in MyArray.
My Ideal output would be:
NewCell1 = {'Name1AA1', 'Name2AA1'}
NewCell2 = {'Name4AB2'}
NewCell3 = {'Name3Acc2'}
ie, no new cell for the code names that are not present in MyArray or no new cell if there is a code name in MyArray but not in MyCell.
Any help is welcome, and thanks for your time
You can use a combination of regular expressions to achieve the desired output. Your approach of wanting to name variables dynamically is not recommended and will lead to code which is harder to debug. Use indexing instead.
You can read this informative post on Matlab's forum to understand why.
%Your input data.
MyArray = ['AA1', 'AA2', 'AB1', 'AB2', 'Acc1', 'Acc2'];
MyCell = {'Name1AA1', 'Name2AA1', 'Name3Acc2', 'Name4AB2', 'Name5AD1'};
%Find common elements between MyArray and MyCell.
elem = cellfun(#(x) regexp(MyArray,x(end-2:end),'match'),MyCell,'un',0);
%Eliminate duplicates.
NewCell = unique([elem{:}]);
%Find elements in MyCell which end with NewCell elements and group them.
NewCell = cellfun(#(x) regexp([MyCell{:}],strcat('Name\d\w?',x),'match'),NewCell,'un',0);
%Join elements.
NewCell{1} = {strjoin(NewCell{1},''',''')};
NewCell{1} = {'Name1AA1','Name2AA1'}
NewCell{2} = {'Name4AB2'}
NewCell{3} = {'Name3Acc2'}
Related
I'm using secondarray as range of cells in a worksheet (Ex. "1", "2") to exclude them as autofilter list that I'm defining in the below function in "filtercriteria".
I get "type mismatch" error in the filter (secondarray) line for some reason, but I works flawlessly when I define an array using a list of items instead. For example, if I use below line to define secondarray instead.
secondarray = ("1", "2")
I've researched similar postings and wasn't lucky, can someone help with this instance?
Thanks,
Dim secondArray As Variant
secondArray = Range("L76:M76").Value
c = 0
k = 0
count = 0
rowNumb = Worksheets("List").Range(Worksheets("List").Range("L5"), Worksheets("List").Range("L5").End(xlDown)).Rows.count
For L = 1 To rowNumb
c = Worksheets("List").Range("L5").Offset(L)
If c <> k Then
'check the current activity type against the array of types we don’t want. If it isn’t in the array we add it to an array that will be used as the filter criteria
If UBound(Filter(secondArray, c)) = -1 Then
ReDim Preserve filterCriteria(0 To count)
filterCriteria(count) = c
count = count + 1
End If
k = c
End If
Next
It isn't working because filter function takes a One-dimensional array of strings to be searched for its sourcearray argument.
When you read in a range from the sheet you automatically get a 2d array as opposed to the 1D you have when assigning from a list.
Find a way to use a 1D array to pass in
For example, as your data is coming from 1 row then slice the array by row
UBound(Filter(Application.WorksheetFunction.Index(secondArray, 1, 0), c)) = -1
You may need to find the right method for you.
Another method is given here.
I have many 33213168x1 cell arrays, where each cell contains an 85 x 1 column.
Each cell in the column is in the form
[0.55;0.25;0.75]
[0.33;0.66;0.99]
I want to split up this single column by the semi-colon delimiter so that each cell in the cell array is 85x3, like:
[0.55][0.25][0.75]
[0.33][0.66][0.99]
I've tried numerous techniques to solve this, but most commonly get the errors 'cell elements must be character arrays' or 'input must be a string.'
Some of the approaches I've tried:
splitcells = strsplit(regress_original_053108,';');
splitcells = cellfun(#(x) strsplit(regress_original_053108, ';'),regress_original_053108 , 'UniformOutput',0);
splitcells = regexp(regress_original_053108, ';', 'split');
splitcells = textscan(regress_original_053108, 'delimiter', ';');
Etc. Any feedback about how to do this would be appreciated.
Hope this solves your problem:
% Example input
input = {[0.55;0.25;0.75]};
cellArray(1:85,1) = input;
% Create array
doubleArray = zeros(85,3);
% Fill array
for i=1:85
doubleArray(i,:) = cellArray{i,1}';
end
Each cell you have is not a string, hence you can't use strsplit. Use this approach:
for ii = length(X) % Here X denotes your 33213168x1 cell array
X{ii} = cell2mat(cellfun(#(y) y.', X{ii}, 'UniformOutput', false));
end
I have a script that searches Twitter for a certain term and then prints out a number of attributes for the returned results.
I'm trying to Just a blank array is returned. Any ideas why?
public_tweets = api.search("Trump")
tweets_array = np.empty((0,3))
for tweet in public_tweets:
userid = api.get_user(tweet.user.id)
username = userid.screen_name
location = tweet.user.location
tweetText = tweet.text
analysis = TextBlob(tweet.text)
polarity = analysis.sentiment.polarity
np.append(tweets_array, [[username, location, tweetText]], axis=0)
print(tweets_array)
The behavior I am trying to achieve is something like..
array = []
array.append([item1, item2, item3])
array.append([item4,item5, item6])
array is now [item1, item2, item3],[item4, item5, item6].
But in Numpy :)
np.append doesn't modify the array, you need to assign the result back:
tweets_array = np.append(tweets_array, [[username, location, tweetText]], axis=0)
Check help(np.append):
Note that
append does not occur in-place: a new array is allocated and
filled.
In the second example, you are calling list's append method which happens in place; This is different from np.append.
Here's the source code for np.append
In [178]: np.source(np.append)
In file: /usr/local/lib/python3.5/dist-packages/numpy/lib/function_base.py
def append(arr, values, axis=None):
....docs
arr = asanyarray(arr)
if axis is None:
.... special case, ravels
return concatenate((arr, values), axis=axis)
In your case arr is an array, starting with shape (0,3). values is a 3 element list. The is just a call to concatenate. So append call is just:
np.concateante([tweets_array, [[username, location, tweetText]]], axis=0)
But concatenate works with many items
alist = []
for ....:
alist.append([[username, location, tweetText]])
arr = np.concatenate(alist, axis=0)
should work just as well; better because list append is quicker. Or remove a level of nesting and let np.array stack them on a new axis, just as it does with np.array([[1,2,3],[4,5,6],[7,8,9]]):
alist = []
for ....:
alist.append([username, location, tweetText])
arr = np.array(alist) # or np.stack()
np.append has multiple problems. Wrong name. Doesn't act inplace. Hides concatenate. Flattens without much warning. Limits you to 2 inputs at a time. etc.
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.
I am new to Matlab and was trying to concatenate array from cell arrays. I have done it as shown below.
S = load('input_file.mat');
c = struct2cell(S);
v = cell2mat(c(1,1));
temp = v(1:500,1:600);
v = cell2mat(c(3,1));
temp1 = v(1:500,1:600);
v = cell2mat(c(2,1));
temp2 = v(1:500,1:600);
v = cell2mat(c(4,1));
temp3 = v(1:500,1:600);
array1 = vertcat(temp,temp1);
array2 = vertcat(temp2,temp3);
But i guess there should be a better way or a direct function call which can get me the same result as i am getting from the code shown?
This is a very specific task, not very general, unless I'm missing the pattern. Starting after struct2cell:
C3 = cellfun(#(x)x(1:500,1:600),c,'uni',0);
array1 = vertcat(C3{[1 3]});
array2 = vertcat(C3{[2 4]});
Although, you could probably get rid of your initial structfun if you replace cellfun above with structfun, taking s as an input. It simply operates on each field.