1

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?

1
  • @knedlsepp thanks for the edit.. sorry if it was annoying to read! Commented Feb 22, 2015 at 21:27

2 Answers 2

2

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.

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

6 Comments

Ah thanks.. I wasn't aware of this cellfun before.. thank you.
@MaheenSiddiqui: You could use a for loop instead of cellfun. The most important fix here is, that you need to use sprintf instead of fprintf.
@knedlsepp - Have you considered using sprintfc? It's an undocumented function: undocumentedmatlab.com/blog/…
@rayryeng: Never heard about it. I guess in this case strcat would suffice. So this is basically cellfun+sprintf for a single cell-array?
Pretty much! You haven't heard of it because it is undocumented after all :) lol. sprintfc is a very powerful function. It essentially takes data and converts it into a cell array of entries. It has been shown that it is much faster than using cellfun with uni=0.
|
2

This can be done very simply with strcat:

C.labels = strcat(A.labels, '-', B);

2 Comments

Ha. Just when I write my comment about strcat, you turn up. :-D
Actually I turned up 13 seconds earlier :-P

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.