use*_*229 18 string matlab cell
假设我有一个细胞
v = 'v' [576.5818] [3.0286] [576.9270]
'v' [576.5953] [3.1180] [576.8716]
'f' [ 56] [ 58] [ 52]
'f' [ 56] [ 58] [ 52]
Run Code Online (Sandbox Code Playgroud)
我想使用每个元素的格式字符串将其转换为单元格数组:' %.5f'
我怎样才能做到这一点?我尝试了以下方法,但是我收到了一个错误:
f1 = @(x) sprintf(' %.5f',x);
cellfun(f1, num2cell(v),'UniformOutput', false)
Run Code Online (Sandbox Code Playgroud)
我收到一个错误???
Error using ==> sprintf
Function is not defined for 'cell' inputs.
Error in ==> @(x)sprintf(' %.5f',x)
任何人都可以提前帮助我
Yau*_*ich 21
好吧,不是真的..这是一个矩阵,但继续阅读.
我猜单元数组是MATLAB中最神秘的数据类型.所以让我们揭开它的神秘面纱 ;-)
假设
fruits = {...
'banana',...
'apple',...
'orange'...
}
Run Code Online (Sandbox Code Playgroud)
首先,小型数组不需要整数索引.使用类似foreach的结构要好得多.确实,
for index = 1:numel(fruits)
fruits{index}
end
Run Code Online (Sandbox Code Playgroud)
相当于
for fruit = fruits
fruit
end
Run Code Online (Sandbox Code Playgroud)
对?
嗯,不太好.第一个循环产生字符串,而第二个循环产生字符串.你可以检查一下
for index = 1:numel(fruits)
[isstr(fruits{index}) iscell(fruits{index})]
end
for fruit = fruits
[isstr(fruit) iscell(fruit)]
end
Run Code Online (Sandbox Code Playgroud)
,即[1 0]和[0 1].
如果你发现了差异,那么你必须知道如何处理下一个例子(在这个例子中你真的与你的问题有关(!)我保证!).假设您尝试在循环中执行水平串联:
for fruit = fruits
[fruit 'is a fruit']
end
Run Code Online (Sandbox Code Playgroud)
你会得到
ans =
'banana' 'is a fruit'
Run Code Online (Sandbox Code Playgroud)
等等.为什么?显然,这段代码试图将嵌套的单元格数组连接成一个字符串(一个包含字符矩阵的单元格数组,构成字符串,如'banana').所以,正确答案是
for fruit = fruits
[fruit{:} 'is a fruit']
end
Run Code Online (Sandbox Code Playgroud)
可悲的是,这已经产生了预期的"香蕉是水果","苹果是水果"等.
一些提示:
for fruit = [fieldnames][1](fruits)'{:} 相当于 cell2mat您的问题的解决方案可能如下所示:
特定
vcell = {...
'v' 576.5818 3.0286 576.9270;
'v' 576.5818 3.0286 576.9270
}
Run Code Online (Sandbox Code Playgroud)
隐式索引仅将数字类型转换为字符串
vcell(cellfun(@isnumeric, vcell)) = cellfun(@(x) sprintf('%.5f', x), vcell(cellfun(@isnumeric, vcell)), 'UniformOutput', false)
Run Code Online (Sandbox Code Playgroud)
以上代码输出
vcell =
'v' '576.58180' '3.02860' '576.92700'
'v' '576.58180' '3.02860' '576.92700'
Run Code Online (Sandbox Code Playgroud)
哪个可以连接.
假设我们有一个单元格如下:
my_cell = {'Hello World'}
class(my_cell)
ans =
cell
Run Code Online (Sandbox Code Playgroud)
我们可以{:}直接使用运算符来获取字符串.
class(my_cell{:})
ans =
char
Run Code Online (Sandbox Code Playgroud)
请注意,我们可以在mycell{:}任何地方使用普通字符串.
| 归档时间: |
|
| 查看次数: |
80426 次 |
| 最近记录: |