2

I have following data:

a=[3 1 6]';
b=[2 5 2]';
c={'ab' 'bc' 'cd'}';

I now want to make a file which looks like this (the delimiter is tab):

ab    3    2
bc    1    5 
cd    6    2

my solution (with a loop) is:

a=[3 1 6]';
b=[2 5 2]';
c={'ab' 'bc' 'cd'}';
c=cell2mat(c);
fid=fopen('filename','w');
for i=1:numel(b)

    fprintf(fid,'%s\t%u\t%u\n',c(i,:),a(i),b(i));

end

fclose(fid);

Is there a possibility without loop and/or the possibility to write cell arrays directly in files?

Thanks.

1 Answer 1

4

How about this:

%A cell array holding all data
%    (Note transpose)
data = cat(2, c, num2cell(a), num2cell(b))';

Write data to a file

fid = fopen('example.txt', 'w');
fprintf(fid, '%s\t%u\t%u\n', data{:});
fclose(fid);

This will be memory wasteful if your datasets get large (probably better to leave then as separate variables and loop), but seems to work.

Sign up to request clarification or add additional context in comments.

1 Comment

Incidentally, it seems like dlmwrite or some variant should be able to do this as well, but I can't seem to find the write call to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.