使用 randperm 在 matlab 中随机排列单词中的字母的函数?从非函数格式更改

Function to shuffle letters in words in matlab using randperm?? Changing from non-function format

我有以下方法可以打乱单词中的字母,但我需要将其更改为要求用户输入单词并输出打乱后的单词的函数形式。 我该怎么做???

word = input('type a word to be scrambled: ', 's');
word(randperm(numel(word)))

你打字的代码确实是正确的。要执行您要求的操作,您实际上只需对上述代码进行一处更改。只需将函数声明放在 .m 文件中,然后将其命名为 scramble.m。然后做:

function word = scramble
    word = input('type a word to be scrambled: ', 's');
    word(randperm(numel(word)))
end

这应该会在您调用该函数时将单词作为字符串输出。所以保存这个文件,然后在命令提示符中输入:

>> word = scramble;

这应该问你要加扰的单词,加扰它和 return 这个单词。这个词存储在 MATLAB 工作区的变量 word 中。


一些建议阅读的内容:http://www.mathworks.com/help/matlab/ref/function.html

MathWorks 的文档非常好,尤其是语法。阅读上面的内容 link 以获取有关如何定义和使用函数的更多详细信息,但其要点是我在上面所做的。

一个matlab函数的一般格式是

    function output = MyFunctionName(input)
    ... code using 'input' goes here
    end % 

如果您有多个输出,请将它们放在一个数组中,最好用逗号分隔。如果您有多个输入,则列出它们并用逗号分隔:

    function [out1, out2,...,outN] = MyFunctionName(input1, input2,...,inputN)
    ... code using the inputs goes here
    end % 

对于您的问题,您没有将单词传递给函数,因此调用函数不需要输入,但您需要从函数内部输入单词。这是一种方法。

    function word = ShuffleLetters
    % Output: 'word' that is shuffled within function
    % Input: none 
    word = input('type a word to be scrambled: ', 's');
    word = word(randperm(numel(word)));
    end

这是一个示例用法:

>> ShuffleLetters
type a word to be scrambled: bacon

ans =

bonca

最后,输入和输出是可选的。这个 m 函数只打印 'Hi!'

    function SayHi
    disp('Hi!')
    end