UPD:我想对StackOverflow社区提出一个问题而不对自己动手解决问题表示抱歉.从现在开始,仅当我确实有严重问题时,我才会问问题
UPD: I wish to say sorry to the StackOverflow community for asking a question without making effort to solve the problem by myself. From now on, I'll ask questions only if I really have serious problem
我现在正在开发生成字符串元素所有可能排列的程序:
I am now developing the program that generates all the possible permutations of string elements:
我从开始:
A = ['Bridge','No Bridge']; B = ['Asphalt','Concrete','Combined']; C = ['Fly Ash',' Sulphur','Nothing']; D = ['Two lanes','Four lanes with barriers']; E = ['Paid','Non-paid']; F = ['Mobile','Non-mobile']; N = length(A)*length(B)*length(C)*length(D)*length(E)*length(F); out = zeros(N,6);但是现在我被下一步该怎么做了.所需的输出类似于:
But now I'm stuck with what to do next. The output needed is something like:
out = 'Bridge' 'Asphalt' 'Fly Ash' 'Two lanes' 'Paid' 'Mobile' 'Bridge' 'Asphalt' 'Fly Ash' 'Two lanes' 'Paid' 'Non-mobile' 'Bridge' 'Asphalt' 'Fly Ash' 'Two lanes' 'Non-paid' 'Mobile' 'Bridge' 'Asphalt' 'Fly Ash' 'Two lanes' 'Non-paid' 'Non-mobile' etc请,您能建议最有效的方法吗?
Please, could you suggest the most efficient way to do this?
推荐答案首先,请注意,在Matlab中,以下方括号表示法:['Hello', 'World'],实际上并不创建字符串数组,而是将字符串"Hello"连接起来. "和世界"生成"HelloWorld".因此,在这种情况下,您应该使用单元格数组:(请注意大括号).
First, note that in Matlab, the following square bracket notation: ['Hello', 'World'], does not in fact create an array of string, but concatenates the strings "Hello" and "World" to yield 'HelloWorld'. So, in this case, you should use Cell Arrays instead: A = {'Hello', 'World'} (note the curly brackets).
要回答您的问题:尽管您可以寻求更通用的东西(您应该在现实生活中的代码中使用),但是现在,由于您知道手的数组,因此可以简单地创建嵌套的for这样的循环:
To answer your question: Although you could go for something more generic (which you should in real-life code), for now, since you know the arrays of hand, you can simply create nested for loops like this:
A = {'Bridge','No Bridge'}; B = {'Asphalt','Concrete','Combined'}; ... for aIndex = 1:length(A) for bIndex = 1:length(B) % add more loop levels here fprintf([A{aIndex}, ',', B{bIndex}, '\n']); end end有产出:
桥梁,沥青 混凝土桥 组合桥 无桥,沥青 无桥,混凝土 无桥组合
Bridge,Asphalt Bridge,Concrete Bridge,Combined No Bridge,Asphalt No Bridge,Concrete No Bridge,Combined