I was wondering if it was possible to use sprintf or fprintf to print something to a cell array.
In a structure A
I have
A.labels = {'A' 'B' 'C' 'D'}
and I have a string/cell array
B = {'E' 'F' 'G' 'H'}
and I want to print into a new structure C
such that I want
C.labels = {'A-E', 'B-F', 'C-G', 'E-H'}
In the code below I am just trying to check how to do the first entry and then once I figure that out I can do the rest myself.
C(1).labels = fprintf('%s -%s',B{1},A(1).labels);
But this does not do the job. How can I fix this?
If you type help fprintf
it says:
fprintf - Write data to text file
But you want help sprintf
:
sprintf - Format data into string
So you can fix your problem using:
C.labels = cellfun(@(x,y) sprintf('%s-%s',x,y), A.labels, B, 'uni',0)
This uses: cellfun
to take corresponding pairs of A.labels
and B
and feeds it to the function @(x,y) sprintf('%s-%s',x,y)
, which uses sprintf
.
You could also use a regular for
loop of course. I want to add also that what you currently have is a structure with a single cell
-entry of length four instead of four structures each having a single entry.