I like to save a cell array into text file

2 views (last 30 days)
Majid Vaghari
Majid Vaghari on 27 Dec 2021
Commented: dpb on 27 Dec 2021
Hello to all,
I have a big cell array and I like to save it into text file.
the cell array contains two columns and each colum contain name of an element for example 'Al'.
a row of the cell array is like: ['Al' 'Mg']
now I'd like to save all of rows into a text file and save it like AlMg no space between Al and Mg in the text file.
for example if in the cell array is :
Al Mg
Na k
Al Sc
in the text file:
AlMg
NaK
AlSc
I attached the Untitled.m file
if you run the program you will get the Binary which is my cell array and I like to save it into a text file like I said above.
Note that the Binary cell array is big array!
best
Majid
  1 Comment
Majid Vaghari
Majid Vaghari on 27 Dec 2021
I use MATLAB 2014b,
Please see the attachment.
best

Sign in to comment.

Accepted Answer

dpb
dpb on 27 Dec 2021
>> c={'Al','Mg';'Na','K'}
c =
2×2 cell array
{'Al'} {'Mg'}
{'Na'} {'K' }
>> join(c,'')
ans =
2×1 cell array
{'AlMg'}
{'NaK' }
>>
So, the solution to your problem is
>> writecell(join(c,''),'joined.txt')
See what we got...
>> type joined.txt
AlMg
NaK
>>
QED
  3 Comments
dpb
dpb on 27 Dec 2021
Be better to put your follow-up comment as comment instead of Answer...
I would not expect any real difference in performance with the upgrade, just user convenience; it reverts to the same low-level io calls in the end, anyways.
You could see if it made any difference at all to do the concatenation first outside the loop, but I'd still expect that to be minimal. If your array is so big as to make the i/o time noticeable, then it must be quite sizable, indeed.
c=strcat(c(i,1),c(i,2)); % join cell array first
fid=fopen(...)
for i=1:size(c,1)
fprintf(fid,'%s\n',c{i,1});
end
or, alternatively, forget about the join entirely...just a little more code in the output is why I didn't before, didn't figure the time factor would be an issue...
...
fprintf(fid,'%s\n',[c{i,}]);
or
fprintf(fid,'%s%s\n',c{i,:});

Sign in to comment.

More Answers (1)

Majid Vaghari
Majid Vaghari on 27 Dec 2021
Thanks for your answer.
I'll update my MATLAB. I have done your older solution version but it takes time for matlab to solve all the cells into one file. So, I was trying to find something faster. So, I think I should upgrade my MATLAB.
beST

Products


Release

R2014b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!