How to substring of a string in matlab array - arrays

I have a matlab cell array of size 20x1 elements. And all the elements are string like 'a12345.567'.
I want to substitute part of the string (start to 9th index) of all the cells.
so that the element in matrix will be like 'a12345.3'.
How can I do that?

You can use cellfun:
M = { 'a12345.567'; 'b12345.567' }; %// you have 20 entries like these
MM = cellfun( #(x) [x(1:7),'3'], M, 'uni', 0 )
Resulting with
ans =
a12345.3
b12345.3
For a more advanced string replacement functionality in Matlab, you might want to explore strrep, and regexprep.

Another method that you can use is regexprep. Use regular expressions and find the positions of those numbers that appear after the . character, and replace them with whatever you wish. In this case:
M = { 'a12345.567'; 'b12345.567' }; %// you have 20 entries like these - Taken from Shai
MM = regexprep(M, '\d+$', '3');
MM =
'a12345.3'
'b12345.3'
Regular expressions is a framework that finds substrings within a larger string that match a particular pattern. In our case, \d is the regular expression for a single digit (0-9). The + character means that we want to find at least one or more digits chained together. Finally the $ character means that this pattern should appear at the end of the string. In other words, we want to find a pattern in each string such that there is a number that appears at the end of the string. regexprep will find these patterns if they exist, and replace them with whatever string you want. In this case, we chose 3 as per your example.

Related

How to store the multiple positions of a character in a string inside an array in free format RPGLE?

In standard RPGLE, my code looks like this. This statement stores the positions of the commas in Data in ComArr array.
C ',' Scan Data ComArr
I tried doing it in free format like this. But all the indices of ComArr array is loaded with the first position of comma in Data. This is because %Scan returns only one position and upon saving it to an array ends up loading the whole array with a single value.
ComArr = %Scan(',':Data) ;
Is there any other method to process SCAN in free format RPGLE like it does in C spec? Basically I want to split the string separated by a delimiter.
One possibility is to keep the C-spec as-is. If the code block needs an array of delimiter positions, and one line of code already does that, put a comment above the fixed-format spec describing what it does and leave it in there.
If /free is required and you don't want to replace the entire block of code, you will need to roll your own loop to build the array of delimiters.
I don't personally convert from fixed to /free unless I am re-writing the block of code to be functionally different. That is, I would almost certainly write a different algorithm in /free than I would have written in fixed. So the entire process of building an array of delimiter positions and then splitting the string based on that array is not something I would do in /free.
I would write a new sub-procedure that returns an array of strings given one delimited input string. The code inside that sub-procedure would make one pass through the input, looking for delimiters with %scan(), and for each one found, split the substring into the next available output array element. There's no need for an array of delimiter positions with this sort of algorithm.
This is probably a little late, but if anyone else needs to split a string by a given delimeter, this code should do what you need.
If you assign a value to an array using wildcard eval array(*) = ..., it applies to every element of the array.
Declare the prototype in your source:
D split pr 1024a varying
D string 65535a varying const options(*varsize)
D delims 50a varying const
D pos 10i 0
Declare a couple of variables.
This assumes your input string is 1000 characters and each separated item is 10 characters maximum:
D idx s 10i 0
D list s 1000a
D splitAry s 10a dim(100)
This is how you split the string.
This tells the routine your delimeter is a comma:
c eval idx = 0
c eval splitAry(*) = split(list:',':idx)
Define the procedure that does the work:
*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
* split - Split delimited string
*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Psplit b export
D split pi 1024a varying
D iString 65535a varying const options(*varsize)
D iDelims 50a varying const
D iPos 10i 0
*
D result s 1024a varying
D start s 10i 0
D char s 1a
*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
c eval start = iPos + 1
c eval %len(result) = 0
*
c for iPos = start to %len(iString)
c eval char = %subst(iString:iPos:1)
c if %check(iDelims:char) = 1
c eval result = result + char
c else
c leave
c endif
c endfor
*
c return result
Psplit e
Don't forget to add dftactgrp(*no) to your H spec if you're defining and using this in the same module!

Matlab join array of strings

In ruby and other languages, I can create an array, push an arbitrary number of strings and then join the array:
ary=[]
...
ary.push some_str
ary.push some_other_str
...
result = ary.join ""
How do I accomplish this in matlab?
User story: my plot legend is composed of a variable number of strings. The number of strings is determined runtime, so I want to declare the array, add strings dynamically and then join the array to the legend string in the end of the script.
In MATLAB, String joining happens like the following
a = 'ding';
b = 'dong';
c = [a ' ' b]; % Produces 'ding dong'
P.S. a typeof(c,'char') shows TRUE in MATLAB because it "joins" all characters into C.
Suppose you want to start with an empty char placeholder. You can do this.
a = ``; % Produces an empty character with 0x0 size.
Then you can keep adding to the end of it; like this:
a = [a 'newly added'] % produces a = "newly added"
To prove that it works, do this again:
a = [a ' appended more to the end.'] % produces a = "newly added appended more to the end."
You can always use the end keyword that points to the last index of an array, but in this case you need to append to end+X where X is the extra number of characters you are appending (annoyingly). I suggest you just use the [] operator to join/append.
There is also this strjoin(C, delim) function which joins a cell C of strings using a delim delimiter (could be whitespace or whatever). But cheap and dirty one is the one I showed above.

Matlab, find common elements of two cell arrays

I have two cell arrays, the sizes are 1x20033 and 1x19. Let's call these two cell arrays as A and B. I want to compare each cell of A with each cell of B to see if there is any common element.
Finally, I need to build a binary matrix and put one when there is a match.
I tried this:
BinaryMatrix=zeros(20033,19);
for i=1:1:20033
for j=1:1:19
match=find(ismember(A{i},B{j}));
if match==1
BinaryMatrix(i,j)= 1;
end
end
end
but I faced this error: "Input A of class double and input B of class cell must be
cell arrays of strings, unless one is a string."
Please tell me What should I do to solve it?
The code that you have almost works. What I would recommend you do is split up the strings found in A and B by spaces. As such, A and B would then be cell arrays of elements where each element in A or B is a single word. The spaces will serve as delimiters for separating out the words.
Once you do this, use intersect to see if there are any common words between the words in A and the words in B. intersect works by considering two arrays (these can be numeric arrays, cell arrays, etc.) C and D as sets, and it returns the set intersection between these two arrays.
In our case, C and D would be a cell array of words separated by spaces from A and B. intersect(C,D) will return a cell array of strings where each element in the output is a string found in both C and D. As such, should this cell array be non-empty, we have found at least one common word between C and D. If this is the case, then set your binary flag at the location of your matrix to 1. In other words:
BinaryMatrix = false(20033,19);
for i=1:1:20033
for j=1:1:19
Asplit = strsplit(A{i});
Bsplit = strsplit(B{j});
if (~isempty(intersect(Asplit, Bsplit)))
BinaryMatrix(i,j)= true;
end
end
end
You'll notice that I have changed your matrix from zeros(20033,19), to false(20033,19). The reason why is because by doing zeros, you are allocating 8 bytes per number in your matrix as this will create your matrix in double precision. By doing false, this will be a logical matrix instead, and you are allocating 1 byte per number. Seeing as how you want BinaryMatrix to be either true or false, don't use double - use logical. I don't know how large both cell arrays are, and so doing this will cut down your memory consumption by 8.
Minor Note
strsplit is only available from R2013a and onwards. If you have a version of MATLAB that is R2012b and lower, replace strsplit with regexp. As such, you would replace the two lines in the for loop with:
Asplit = regexp(A{i}, ' ', 'split');
Bsplit = regexp(B{j}, ' ', 'split');

Algorithm - check if any string in an array of strings is a prefix of any other string in the same array

I want to check if any string in an array of strings is a prefix of any other string in the same array. I'm thinking radix sort, then single pass through the array.
Anyone have a better idea?
I think, radix sort can be modified to retrieve prefices on the fly. All we have to do is to sort lines by their first letter, storing their copies with no first letter in each cell. Then if the cell contains empty line, this line corresponds to a prefix. And if the cell contains only one entry, then of course there are no possible lines-prefices in it.
Here, this might be cleaner, than my english:
lines = [
"qwerty",
"qwe",
"asddsa",
"zxcvb",
"zxcvbn",
"zxcvbnm"
]
line_lines = [(line, line) for line in lines]
def find_sub(line_lines):
cells = [ [] for i in range(26)]
for (ine, line) in line_lines:
if ine == "":
print line
else:
index = ord(ine[0]) - ord('a')
cells[index] += [( ine[1:], line )]
for cell in cells:
if len(cell) > 1:
find_sub( cell )
find_sub(line_lines)
If you sort them, you only need to check each string if it is a prefix of the next.
To achieve a time complexity close to O(N2): compute hash values for each string.
Come up with a good hash function that looks something like:
A mapping from [a-z]->[1,26]
A modulo operation(use a large prime) to prevent overflow of integer
So something like "ab" gets computed as "12"=1*27+ 2=29
A point to note:
Be careful what base you compute the hash value on.For example if you take a base less than 27 you can have two strings giving the same hash value, and we don't want that.
Steps:
Compute hash value for each string
Compare hash values of current string with other strings:I'll let you figure out how you would do that comparison.Once two strings match, you are still not sure if it is really a prefix(due to the modulo operation that we did) so do a extra check to see if they are prefixes.
Report answer

DNA extraction python

Now, I need to find a way in which Python can find the codon position number 5 of the above code and extract that sequence until position 12 (ATGG*CTTTACCTCGTC*TCACAGGAG). So the output should be something like this:
>CCODE1112_5..11
CTTTACCTCGTC
How can I tell python to get the begin value after the first "_" and the end value after ".." so it can do it automatically? ? THANKS!!!
def extractseq( queryseq , begin=5, end =12):
queryseq=queryseq.split('\n')#transform the string in a list of lines included in the string
return queryseq[1][begin-1:end-1]
I think this function should work, beware of the index which begin at 0 in python
after written that in your script you just have to call the function subs=extractseq(seq,5,12)
ok sorry so if you want to extract the 5 and the 12 included in the substring one way to do that easly is:
substring=queryseq.split('\n')[0].split('_')[1].split('...')#extraction of the substring
begin=substring[0]
end = substring[1]
I'd probably (sigh) use a regex to extract 5 and 12 from CCODE1112_5..12_ABC.
Then convert the extracted strings to int's.
Then use the int's as indexes in a string slice on the DNA data.
For the regex:
regex = re.compile(r'^[^]*(\d+)..(\d+)_.*$')
regex.match('CCODE1112_5..12_ABC')
match = regex.match('CCODE1112_5..12_ABC')
match.group(1)
'5'
match.group(2)
'12'
To convert those to int's, use int(match.group(1)), for example.
Then your indices are 1-based, while python's are 0-based. Also, python's starting point for a slice is at the value you want, and python's ending point for a slice is one past the value you want. So subtract one from group(1) and leave group(2) alone.
So something like:
substring = dna_data[left_point-1:right_point]

Resources