如何转换char到matlab中的数字? [英] how to convert char to number in matlab?

查看:3842
本文介绍了如何转换char到matlab中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助我解决以下问题:

Please help me with the following problem:

在matlab中,我有一个Nx3字符变量,其中N可以根据输入变化。
假设N = 5,我有以下变量A(5x3 char):

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']

有一种方法来定义一个新的变量B变量A中的数字,即 B = [1; 5; 10; 15; 20]

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]?

感谢您的帮助!

推荐答案

由于你的输入是一个字符数组,首先将每行转换成一个单元格以允许使用MATLAB中的字符串函数:

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 将矩阵转换为一系列单元格。在我们的示例中,您希望有5个单元格,或者与矩阵中的行数相同的单元格 val ,每个单元格将与列的总数一样长 val

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.

一旦你这样做,你可以替换 Y 无字符串,然后转换为数字:

Once you do this, you can replace the Y strings with nothing, then convert to numbers:

out = strrep(out, 'Y', '');
out2 = cellfun(@str2num, out);

第一行使用 strrep 替换 Y 没有任何内容,然后我们应用 str2num ,以将修剪后的字符串转换为实际数字。这是通过使用 cellfun ,以便我们可以遍历每个单元格对每个单元格应用 str2num

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.

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);

这篇关于如何转换char到matlab中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆