0

I want to export several cell arrays of string to a text file, using a loop, in a way very similar to the one explained in the following link:

http://www.mathworks.com/examples/matlab/1107-export-cell-array-to-text-file

The only difference is that everyone of the arrays has a different number of columns and I don't know how to tell formatspec to create that number of columns for each array in every iteration of the loop.

I need a command that tells

if myarray has 2 columns
formatSpec = '%s %s';
else if myarray has 3 columns
formatSpec = '%s %s %s\n';
else
...

I tried to simply set formatspec to 10 columns as the arrays don't contain more than that, but then the output file isn't organized in rows.

Thanks in advance for your help,

0

1 Answer 1

0

What about something like this:

%// Get number of columns
NumCol = size(myarray,2)

%// Define basic format spec to be repeated
baseString = ['%s'];

%// Generate actual formatSpec to be used
formatSpec = repmat(baseString,1,NumCol)

%// Add \n at the end
out = fprintf([formatSpec '\n'],myarray)

You could modify this and include it in an if-else or switch/case block if you want but that should be general enough.

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

2 Comments

thanks for your answer! I found a mistake when defining the format. inline baseString = ['%s ']; %add a space in the format inline formatSpec = repmat(baseString,1,NumCol-1) inline out = fprintf([formatSpec '%s\r\n'],myarray) %Althought, I'm still struggling to get the output separated in lines
Actually, the problem was solved with this amendment.

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.