0

为了

A=[100;300;1000;240]

B=cell(8,1)

我将以下结果存储在 B

[100]
[300]
[1000]
[240]
[100;300;240]
[100;1000]
[300;1000]
[100;300;1000]

我想打印这些以将输出显示为:

choose first
choose second
choose third
choose fourth
choose first or second or fourth
choose first or third
.
.
etc

基本上,从数组A=[100;300;1000;240]中,我希望其中的每个值都由一个字符串表示,而不是一个变量。知道怎么做吗?


笔记 :

对于我的代码,我希望用户在数组A中输入他们自己的数字,因此A的长度是可变的,可以大于 4。单元格B的大小也会根据公式而变化,因此它并不总是固定的尺寸为 8。


我也很欣赏一个简单的代码,不要太复杂(除非必要),因为我没有 matlab 的专业知识。更简单的代码可以帮助我理解和学习。

4

3 回答 3

1

对于映射,我只会使用地图对象

index_to_string = containers.Map(keySet,valueSet)

在哪里

keySet = 1:20
valueSet = {'first'; 'second'; ...; 'twentieth'}

如果A在打印前可用,您可以使用相同的valueSet,只需将其切成A.

index_to_string = containers.Map(A,valueSet(1:length(A)))

例子:

G = cell(size(B))
for i = 1:length(B)
    out1 = 'choose ';
    if len(B{i}) == 1
        out1 = [out1, index_to_string(B{i})];
    else
        temp = B{i}
        for j=1:(length(temp)-1)
            out1 = [out1, index_to_string(temp(j)), ' or ' ];
        end
        out1 = [out1, index_to_string(temp(end))];
    end
    G{i} = out1
end
于 2013-03-06T23:32:59.740 回答
0

这是我的做法

function IChooseYouPikachu(Choices, Results)
% put in A for choices and B for results

%simple boolean to indicate whether a choice has been made already
answerChosen = 0;

for k = 1:length(Results)
    Response = 'choose';
    for m =  1:length(Choices)
        if any(Results{k} == Choices(m))
            if answerChosen
                Response = [Response ' or ' NumToOrd(m)];
            else
                answerChosen = 1;
                Response = [Response ' ' NumToOrd(m)];
            end
        end
    end
    fprintf('%s\n',Response);
    answerChosen = 0;
end

function ordinal = NumToOrd(number)
switch number
    case 1, ordinal = 'first';
    case 2, ordinal = 'second';
    case 3, ordinal = 'third';
    case 4, ordinal = 'fourth';
    otherwise, ordinal = 'out of index';
end
于 2013-03-06T23:22:05.193 回答
0

这个答案完全基于JaredS's答案。我刚刚澄清了你的疑惑。

把它写在一些m文件中。

Choices=A; Results=B;
%simple boolean to indicate whether a choice has been made already
answerChosen = 0;

for k = 1:length(Results)
    Response = 'choose';
    for m =  1:length(Choices)
        if any(Results{k} == Choices(m))
            if answerChosen
                Response = [Response ' or ' NumToOrd(m)];
            else
                answerChosen = 1;
                Response = [Response ' ' NumToOrd(m)];
            end
        end
    end
    fprintf('%s\n',Response);
    answerChosen = 0;
 end

请把下面的函数写在一个单独的文件中,并把它放在与前面的m文件相同的目录下。然后你应该得到一个错误说:"Undefined function 'NumToOrd' for input arguments of type 'double'."

function ordinal = NumToOrd(number)
switch number
    case 1, ordinal = 'first';
    case 2, ordinal = 'second';
    case 3, ordinal = 'third';
    case 4, ordinal = 'fourth';
    otherwise, ordinal = 'out of index';
end
于 2013-03-07T01:19:29.233 回答