I want to remove characters within parentheses from a string in MATLAB:
For eg: I have the string
S(+42.01)DKHDKPDISEVTKFDKSKLKKTETHEKNPLPTKETIDQEKQG
but want to remove the parentheses and store :
SDKHDKPDISEVTKFDKSKLKKTETHEKNPLPTKETIDQEKQG
The characters in parentheses could be text, numbers, combination of text numbers and special characters. Also the parentheses can occur multiple times in the same string.
Thanks
There you go:
x = 'Q(-17.03)VAQMHVWRAVNHDRNHGTGSGRH(-.98)';
y = regexprep(x, '\([^\(\)]*\)',''); % detect substring formed by
% parentheses and anything in between that is not a parenthesis,
% and replace that by an empty string
gives
y =
QVAQMHVWRAVNHDRNHGTGSGRH
Related
I have a char array of format a = [1.234 ; 2.345; 3.456] and I need to convert this to a numeric array in MATLAB. I have tried str2num(a) but it only seems to work on integers, as it is returning an empty vector. Here is what the data actually looks like:
Any suggestions on how to tackle this problem are appreciated!
If your character array is either of the following formats:
a = '[1.234; 2.345; 3.456]'; % 1-by-N with brackets, spaces, or semicolons
a = ['1.234'; '2.345'; '3.456']; % M-by-N
Then str2num should work as you want:
vec = str2num(a)
vec =
1.234000000000000
2.345000000000000
3.456000000000000
If it's not working then that probably means that your character array val has rows with invalid formats or characters that don't properly convert. Since the array has 3100 rows, you probably don't want to search through it by hand. One easy way to highlight where invalid rows might be is to identify where there are characters other than numbers, periods, or white space. Here's how you can get a list of rows that may warrant further inspection:
suspiciousRows = find(~all(ismember(val, '0123456789. '), 2));
The function str2double would works for your case. Please refer to this link for detailed usage.
str2num would work as it is but as str2num uses eval,so a better alternative is str2double. But it is not directly applicable on a char array like yours. You can convert that array into a cell using cellstr and then apply str2double.
req = str2double(cellstr(val))
Another approach if you have MATLAB R2016b or a later version is to convert that char array into a string array and then apply str2double.
req = str2double(string(val))
Can some one explain what this line here does? This is part of an old matlab code I need to reuse for my work
matdir = [params.ariens '-' num2str(dirtimes(ii))];
I'm especially confused about the '-' part. Thanks a lot in advance.
Single quotes are used to create a string literal so '-' simply creates a string containing the hyphen character. In MATLAB, [ ... ] performs horizontal concatenation so the line that you have shown concatenates the string stored in params.ariens, the character '-' and the number dirtimes(ii) converted to a string using num2str to creat one long string made up of those three strings.
For example:
c = ['abc', '-', 'def']
% abc-def
class(c)
% char
d = ['abc', '-', num2str(10)]
% abc-10
I have an cell-array of dimensions 1x6 like this:
A = {'25_2.mat','25_3.mat','25_4.mat','25_5.mat','25_6.mat','25_7.mat'};
I want to read for example from the A{1} , the number after the '_' i.e 2 for my example
Using cellfun, strfind and str2double
out = cellfun(#(x) str2double(x(strfind(x,'_')+1:strfind(x,'.')-1)),A)
How does it work?
This code simply finds the index of character one number after the occurrence of '_'. Lets call it as start_index. Then finds the character one number lesser than the index of occurrence of '.' character. Lets call it as end_index. Then retrieves all the characters between start_index and end_index. Finally converts those characters to numbers using str2double.
Sample Input:
A = {'2545_23.mat','2_3.mat','250_4.mat','25_51.mat','25_6.mat','25_7.mat'};
Output:
>> out
out =
23 3 4 51 6 7
You can access the contents of the cell by using the curly braces{...}. Once you have access to the contents, you can use indexes to access the elements of the string as you would do with a normal array. For example:
test = {'25_2.mat', '25_3.mat', '25_4.mat', '25_5.mat', '25_6.mat', '25_7.mat'}
character = test{1}(4);
If your string length is variable, you can use strfind to find the index of the character you want.
Assuming the numbers are non-negative integers after the _ sign: use a regular expression with lookbehind, and then convert from string to number:
numbers = cellfun(#(x) str2num(x{1}), regexp(A, '(?<=\_)\d+', 'match'));
I have a string and I need two characters to be returned.
I tried with strsplit but the delimiter must be a string and I don't have any delimiters in my string. Instead, I always want to get the second number in my string. The number is always 2 digits.
Example: 001a02.jpg I use the fileparts function to delete the extension of the image (jpg), so I get this string: 001a02
The expected return value is 02
Another example: 001A43a . Return values: 43
Another one: 002A12. Return values: 12
All the filenames are in a matrix 1002x1. Maybe I can use textscan but in the second example, it gives "43a" as a result.
(Just so this question doesn't remain unanswered, here's a possible approach: )
One way to go about this uses splitting with regular expressions (MATLAB's strsplit which you mentioned):
str = '001a02.jpg';
C = strsplit(str,'[a-zA-Z.]','DelimiterType','RegularExpression');
Results in:
C =
'001' '02' ''
In older versions of MATLAB, before strsplit was introduced, similar functionality was achieved using regexp(...,'split').
If you want to learn more about regular expressions (abbreviated as "regex" or "regexp"), there are many online resources (JGI..)
In your case, if you only need to take the 5th and 6th characters from the string you could use:
D = str(5:6);
... and if you want to convert those into numbers you could use:
E = str2double(str(5:6));
If your number is always at a certain position in the string, you can simply index this position.
In the examples you gave, the number is always the 5th and 6th characters in the string.
filename = '002A12';
num = str2num(filename(5:6));
Otherwise, if the formating is more complex, you may want to use a regular expression. There is a similar question matlab - extracting numbers from (odd) string. Modifying the code found there you can do the following
all_num = regexp(filename, '\d+', 'match'); %Find all numbers in the filename
num = str2num(all_num{2}) %Convert second number from str
I am trying to add '\' before all special characters in a string in MATLAB, could anyone please help me out. Here is the example:
tStr = 'Hi, I'm a Big (Not So Big) MATLAB addict; Since my school days!';
I want this string to be changed to:
'Hi\, I\'m a Big \(Not so Big \) MATLAB addict\; Since my school days\!'
The escape character in Matlab is the single quote ('), not the backslash (\), like in C language. Thus, your string must be like this:
tStr = 'Hi\, I\''m a Big (Not so Big ) MATLAB addict\; Since my school days!'
I took the list of special charecters defined on the Mathworks webpage to do this:
special = '[]{}()=''.().....,;:%%{%}!#';
tStr = 'Hi, I''m a Big (Not So Big) MATLAB addict; Since my school days!';
outStr = '';
for l = tStr
if (length(find(special == l)) > 0)
outStr = [outStr, '\', l];
else
outStr = [outStr, l];
end
end
which will automatically add those \s. You do need to use two single quotes ('') in place of the apostrophe in your input string. If tStr is obtained with the function input(), or something similar, this will procedure will still work.
Edited:
Or using regular expressions:
regexprep(tStr,'([[\]{}()=''.(),;:%%{%}!#])','\\$1')