我有一个字符串单元格数组(c),其中一些数字标有“#”,并且我有一个尺寸相同(5x6)的矩阵(数据)。
如果“ c”具有标有“#”的数字,那么我想在“数据”相同位置中的数字替换为包含“#”的字符串。
例如,data(1,1)应该为“#2.537”。输出应类似于以下脚本生成的“ dataT1_2”单元格数组。下面的代码可以正常工作,但是我认为它有点笨拙和新手。
try {
$path = 'C:\\wamp64\\apps\\scilab-5.5.2\\bin\\Scilex.exe';
$path_script = "ea=loadfls('C:\\wamp64\\www\\scilab\\estilosaprendizaje.fls');res=evalfls([-11,11],ea); disp(res);exit;";
$command = $path . ' -nb -e "' . $path_script.'"';
echo $command;
exec($command, $output);
foreach ($output as $line) {
print_r($line);
echo "<br />";
}
} catch (Exception $e) {
echo 'Excepción capturada: ', $e->getMessage();
}
答案 0 :(得分:1)
基本上,您需要学习如何使用逻辑索引,例如
>> tmp = cellfun(@num2str,num2cell(data),'uni',false); % convert to strings
>> loc = contains(c,'#') % get locations of elements with a #
loc =
5×6 logical array
1 0 0 0 1 0
0 1 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
>> tmp(loc) = c(loc) % replace elements
tmp =
5×6 cell array
{'# 2.537'} {'0.0975' } {'0.1576'} {'0.1419'} {'# 0.120'} {'0.7577'}
{'0.9058' } {'# 1.400'} {'0.9706'} {'0.4218'} {'0.0357' } {'0.7431'}
{'0.127' } {'0.5469' } {'0.9572'} {'0.9157'} {'0.8491' } {'0.3922'}
{'0.9134' } {'0.9575' } {'0.4854'} {'0.7922'} {'0.934' } {'0.6555'}
{'0.6324' } {'0.9649' } {'0.8003'} {'0.9595'} {'0.6787' } {'0.1712'}
编辑: 根据您的评论,第三行更改为:
>> tmp(loc) = cellfun(@(x)sprintf('# %s',x),tmp(loc),'uni',false)
tmp =
5×6 cell array
{'# 0.8147'} {'0.0975' } {'0.1576'} {'0.1419'} {'# 0.6557'} {'0.7577'}
{'0.9058' } {'# 0.2785'} {'0.9706'} {'0.4218'} {'0.0357' } {'0.7431'}
{'0.127' } {'0.5469' } {'0.9572'} {'0.9157'} {'0.8491' } {'0.3922'}
{'0.9134' } {'0.9575' } {'0.4854'} {'0.7922'} {'0.934' } {'0.6555'}
{'0.6324' } {'0.9649' } {'0.8003'} {'0.9595'} {'0.6787' } {'0.1712'}
编辑2 :
如果您使用的旧版MATLAB没有功能contains
,则可以将相应的行替换为
>>loc = cellfun(@(x)~isempty(strfind(x,'#')),c);