如何在Matlab中将存储在单元格中的值打印为字符串(整个单词)?

时间:2013-03-06 22:27:13

标签: arrays string matlab printf

有关

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的专业知识。更简单的代码可以帮助我理解和学习。

3 个答案:

答案 0 :(得分:1)

用于映射我只使用map object

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

答案 1 :(得分: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

答案 2 :(得分: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