Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何提取不同长度的子字符串?_String_Matlab_Cell Array - Fatal编程技术网

String 如何提取不同长度的子字符串?

String 如何提取不同长度的子字符串?,string,matlab,cell-array,String,Matlab,Cell Array,我有一个nx2矩阵,它包含指定字符串的子字符串的开始和结束索引。如何在没有for循环的情况下提取子字符串的n by 1单元格数组 string='helloworld!'; 范围=[1; 2 3; 4 5; 3 7]; 子字符串=单元格(大小(范围1),1); 对于i=1:大小(范围,1) 子字符串{i}=string(范围(i,1):范围(i,2)); 结束 预期结果: 您可以使用cellfun使其成为单行操作: str='helloworld!'; 范围=[1; 2 3; 4 5; 3 7

我有一个
nx2
矩阵,它包含指定字符串的子字符串的开始和结束索引。如何在没有for循环的情况下提取子字符串的
n by 1
单元格数组

string='helloworld!';
范围=[1;
2 3;
4 5;
3 7];
子字符串=单元格(大小(范围1),1);
对于i=1:大小(范围,1)
子字符串{i}=string(范围(i,1):范围(i,2));
结束
预期结果:


您可以使用
cellfun
使其成为单行操作:

str='helloworld!';
范围=[1;
2 3;
4 5;
3 7];
%首先将“范围”转换为单元格对象
起重机=mat2cell(范围,单位(尺寸范围,1),1),2);
%在每行/每项“起重机”上调用“cellfun”
cellfun(@(x)str(x(1):x(2)),Cranges,'UniformOutput',假)
ans=

4×1单元阵列

{'H'    }
{'el'   }
{'lo'   }
{'llo W'}
我已将变量
string
更改为
str
,因为
string
是MATLAB中的本机函数(将输入转换为字符串类型)

虽然这是单线操作,但并不意味着效率更高:

Num=1000000;
子字符串=单元格(大小(范围1),1);
%循环时间
抽搐
对于j=1:Num
对于i=1:大小(范围,1)
子串{i}=str(范围(i,1):范围(i,2));
结束
结束
toc;
起重机=mat2cell(范围,单位(尺寸范围,1),1),2);
%时间函数调用
抽搐
对于j=1:Num
子串=cellfun(@(x)str(x(1):x(2)),Cranges,'UniformOutput',false);
结束
toc;

您可以使用
cellfun
使其成为单行操作:

str='helloworld!';
范围=[1;
2 3;
4 5;
3 7];
%首先将“范围”转换为单元格对象
起重机=mat2cell(范围,单位(尺寸范围,1),1),2);
%在每行/每项“起重机”上调用“cellfun”
cellfun(@(x)str(x(1):x(2)),Cranges,'UniformOutput',假)
ans=

4×1单元阵列

{'H'    }
{'el'   }
{'lo'   }
{'llo W'}
我已将变量
string
更改为
str
,因为
string
是MATLAB中的本机函数(将输入转换为字符串类型)

虽然这是单线操作,但并不意味着效率更高:

Num=1000000;
子字符串=单元格(大小(范围1),1);
%循环时间
抽搐
对于j=1:Num
对于i=1:大小(范围,1)
子串{i}=str(范围(i,1):范围(i,2));
结束
结束
toc;
起重机=mat2cell(范围,单位(尺寸范围,1),1),2);
%时间函数调用
抽搐
对于j=1:Num
子串=cellfun(@(x)str(x(1):x(2)),Cranges,'UniformOutput',false);
结束
toc;
请参阅和两个相关问题。请参阅和两个相关问题。
Elapsed time is 3.929622 seconds. 
Elapsed time is 50.319609 seconds.