Search code examples
arraysmatlabfileloopscell

Matlab: cell to file


I am trying to make a vertical histogram, where the user inputs 10 values and output shows as many '*' vertically corresponding to the 10 values.

so i have the array narray narray =

narray = 

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

each cell contains a mixture of blank spaced cell and * for eg

narray{2}

ans =

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

I wanted to print each row of the cell to a file, i tried this

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

but it shows error

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});

here is my full code,

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

I am supposed to get output like this, for the input values 2,1,2,1,2,1,2,1,2,1

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

Solution

  • Edit: corrected syntax

    A great code to do this is cell2csv so all you would need to do is say

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

    A better way to do your program without the loops though is

    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
    

    So if we use your example

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

    Contents of star.txt are

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