1

I'm looking to display data in two columns. The first column will have a movies name and the second a rating out of 5. I want the data to be displayed in such a way that the ratings, regardless of the length of the movie title all display in on vertical line. I currently have:

Toy Story (1995) :   4
GoldenEye (1995) :   3
Seven (Se7en) (1995) :   4
Braveheart (1995) :      1
Bad Boys (1995) :    3
Batman Forever (1995) :      2
Star Wars (1977) :   5
Shawshank Redemption, The (1994) :   5
Ace Ventura: Pet Detective (1994) :      3
Aladdin (1992) :     3

I'm using the following code:

fprintf('%s : \t %d\n', movieList{i},user_ratings(i));

where the above line is obviously in a loop. I tried using a tab to see if things would line up but clearly not much luck. Any ideas on how I could achieve this?

2 Answers 2

3

If you would like to keep things simple and your loop, you may try this -

lens = cellfun(@numel,movieList);
pdlens = max(lens) - lens;
for k = 1:numel(movieList)
    fprintf('%s%s :\t%d\n', movieList{k},repmat(' ',1,pdlens(k)),user_ratings(k))
end

Output -

Toy Story (1995)                  : 4
GoldenEye (1995)                  : 3
Seven (Se7en) (1995)              : 4
Braveheart (1995)                 : 1
Bad Boys (1995)                   : 3
Batman Forever (1995)             : 2
Star Wars (1977)                  : 5
Shawshank Redemption, The (1994)  : 5
Ace Ventura: Pet Detective (1994) : 3
Aladdin (1992)                    : 3

Alternate solution based on arrayfun -

spc = repmat(' ',numel(movieList),1)
pdc = arrayfun(@(x,t) repmat(x,1,t),spc,pdlens,'uni',0) %//pdlens is from earlier code
spcell = repmat(cellstr({'   '}),numel(movieList),1)
out = strcat(movieList,pdc,':',spcell,num2str(user_ratings')) %//'
char(out) %// Display the text
Sign up to request clarification or add additional context in comments.

1 Comment

@AlexandreBizeau Thanks! I am sure there are alternative solutions to this!
0

You can try this, it really not beautifull but :

maxVal = 0
[~,nbMovie] = size(movieList);
for i = 1:nbMovie
    maxVal = max(maxVal,length(movieList{i}))
end

wordPrint = strcat('%',int2str(maxVal),'s');
totalPrint = strcat(wordPrint,' : %f\n');

for i = 1:nbMovie
   fprintf(totalPrint ,movieList{i},user_ratings(i));
end

EDIT

And for a left align for the word use the symbol '-' before the number, like this :

wordPrint = strcat('%-',int2str(maxVal),'s');

Comments

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.