string 迭代 MATLAB 中的字符串列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10687611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Iterating over a list of strings in MATLAB
提问by wanderingbear
I'm trying to iterate over a list of strings in MATLAB. The problem is that, inside the 'for' loop, my iterator is considered a 'cell' rather than a string.
我正在尝试遍历 MATLAB 中的字符串列表。问题是,在“for”循环中,我的迭代器被视为“单元格”而不是字符串。
for str = {'aaa','bbb'}
fprintf('%s\n',str);
end
??? Error using ==> fprintf
Function is not defined for 'cell' inputs.
What is the correct\elegant way to fix this?
解决此问题的正确\优雅方法是什么?
回答by petrichor
You should call the cell's content via str{1}
as follows to make it correct:
您应该通过str{1}
以下方式调用单元格的内容以使其正确:
for str = {'aaa','bbb'}
fprintf('%s\n',str{1});
end
Here's a more sophisticated exampleon printing contents of cell arrays.
这是一个关于打印元胞数组内容的更复杂的示例。
回答by KitsuneYMG
str={'aaa','bbb'};
fprintf('%s\n',str{:});
No need for for
loops.
不需要for
循环。
EDIT:
See also: cellfun
编辑:另见: cellfun
回答by joalv
Starting with R2016b you can use string arrays:
从 R2016b 开始,您可以使用字符串数组:
for str = ["aaa" "bbb"]
fprintf('%s\n',str);
end