问题
Please help me with the following problem:
In matlab, I have an Nx3 char variable, where N can vary depending on the input. Let's say N = 5 and I have the following variable A (5x3 char):
A = [' 1Y';
' 5Y';
'10Y';
'15Y';
'20Y']
Is there a way to define a new variable B having as values the numbers in variable A, i.e. B=[1; 5; 10; 15; 20]
?
Thank you for your help!
回答1:
Since your input is a character array, first convert each row into a cell to allow use with the string functions in MATLAB:
out = mat2cell(val, ones(size(val,1),1));
mat2cell converts a matrix into a series of cells. In our case, you would like to have 5 cells, or as many cells as there are rows in your matrix val
and each cell will be as long as the total number of column in val
.
Once you do this, you can replace the Y
strings with nothing, then convert to numbers:
out = strrep(out, 'Y', '');
out2 = cellfun(@str2num, out);
The first line uses strrep to replace any instances of Y
with nothing, and then we apply str2num on each of the cells to convert the trimmed string into an actual number. This is through the use of cellfun so that we can iterate through each cell apply str2num
to each cell.
We get:
out2 =
1
5
10
15
20
To be fully reproducible:
val = ['1Y '; '5Y '; '10Y'; '15Y'; '20Y'];
out = mat2cell(val, ones(size(val,1),1), size(val,2));
out = strrep(out, 'Y', '');
out2 = cellfun(@str2num, out);
回答2:
Suppose you have the following:
A = [' 1Y';
' 5Y';
'10Y';
'15Y';
'20Y';]
Then this should do the trick:
B=A'
C=strsplit(B(:)','Y')
V=cellfun(@str2num,C(1:end-1))
来源:https://stackoverflow.com/questions/31880545/how-to-convert-char-to-number-in-matlab