Matlab:单元格到文件

Matlab: cell to file

我正在尝试制作垂直直方图,其中用户输入 10 个值,输出显示与 10 个值垂直对应的“*”。

所以我有数组 narray narray =

narray = 

{1x10 cell}
{1x10 cell}
{1x10 cell}
{1x10 cell}
{1x10 cell}
{1x10 cell}
{1x10 cell}
{1x10 cell}
{1x10 cell}
{1x10 cell}

每个单元格包含空格单元格 </code> 和 <code>* 的混合,例如

narray{2}

ans =

' '    '*'    ' '    '*'    ' '    '*'    ' '    '*'    ' '    '*'

我想将单元格的每一行打印到一个文件中,我试过了

fid = fopen('star.txt','wt')

for i =1:10
    fprintf(fid,'%s%s%s%s%s%s%s%s%s%s', narray{i});
end
fclose(fid);
type star.txt

但它显示错误

Error using ==> fprintf
Function is not defined for 'cell' inputs.

Error in ==> test2 at 41
    fprintf(fid,'%s%s%s%s%s%s%s%s%s%s', narray{i});

这是我的完整代码,

n= cell(10,1);

%% // Taking input
for i = 1:10
prompt = 'Numbers bitch :  ';
n{i}{1} = input(prompt);
end
array =cell(10,1);


%% // Storing Input in cell
for i=1:10
    for j=1:10;
        array{i}{j} = ' ';
    end
end

for i = 1:10
    for j=1:n{i}{1}
        array{i}{j}='*';
    end
end

for i= 1:10;
array{i} = array{i}';
end

array=array';
narray=cell(10,10);
for i=1:10
    for j=1:10
        narray{i}{j} = array{j}{i};
    end
end
narray=narray(:,1);

%% // Printing Cell
fid = fopen('C:\Users\harsh\Documents\MATLAB\star.txt','wt')

for i =1:10
    fprintf(fid,'%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n', narray{i};
end
fclose(fid);
type star.txt

对于输入值,我应该得到这样的输出 2,1,2,1,2,1,2,1,2,1

*********
* * * * * 

编辑:更正语法

执行此操作的一个很好的代码是 cell2csv 所以您需要做的就是说

cell2csv('star.txt', narray, '')

一个更好的不用循环来编写程序的方法是

function writeHist(varargin)
    %% input hist
    if nargin == 0
        nInputs = input('Please enter number of inputs: ');
        n = zeros(nInputs,1);

        %% // Taking input
        for i = 1:nInputs
            n(i) = input(['Enter input ', num2str(i),': ']);
        end
    else
        n = varargin{1};

        if ~isvector(n) || ~isnumeric(n)
            disp({'Please either do not enter an input arguement or enter a vector'})
        end
    end

    % Prepare hist
    array = num2cell(cell2mat(arrayfun(@(i) [repmat('*', 1, i), repmat(' ', 1, max(n(:)) - i)], n(:), 'uni', 0)),1)';

    %% Printing hist
    cell2csv('star.txt', array, '')

end

所以如果我们使用你的例子

writeHist([2,1,2,1,2,1,2,1,2,1])

star.txt 的内容是

**********
* * * * * 

好的,这解决了我的问题

for i =1:10
    fprintf(fid,'%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t\n', vertcat(narray{i}{:}));
    fprintf(fid,'\n');
end
fclose(fid);