MATLAB Answers

Use of loops to print the contents of a cell array with varying number of rows

3 views (last 30 days)
Bob Sherland
Bob Sherland on 25 Apr 2018
Edited: Stephen on 25 Apr 2018
So I have a cell array called cell array called system in which I have
system={'file one' 'author one' [100]; 'file two' 'author two' [100]; 'file three' 'author three; [100]}
And I am wondering what process I can use to get an output of
Title: file one
Author: author one
No_pages: 100
Title: file two
Author: author two
No_pages: 100
Title: file three
Author: author three
No_pages: 100
And I need to process to work a cell array with more rows, how exactly should I structure the loop to go through and print the display as shown above?

Answers (2)

Stephen
Stephen on 25 Apr 2018
Edited: Stephen on 25 Apr 2018
No loops are required, just transpose the cell array and use a comma-separated list:
>> C = {'file one','author one',100;'file two','author two',100;'file three','author three',100};
>> fmt = 'Title: %s\nAuthor: %s\nNo. pages: %d\n\n';
>> tmp = C.';
>> fprintf(fmt,tmp{:})
Title: file one
Author: author one
No. pages: 100
Title: file two
Author: author two
No. pages: 100
Title: file three
Author: author three
No. pages: 100
Why make things more complicated than they need to be?

Benjamin Großmann
Benjamin Großmann on 25 Apr 2018
Use a struct array instead of cell array and then disp inside an arrayfun:
clearvars
close all
clc
system(1).Title = 'file one';
system(1).Author = 'author one';
system(1).No_pages = 100;
system(2).Title = 'file two';
system(2).Author = 'author two';
system(2).No_pages = 100;
system(3).Title = 'file three';
system(3).Author = 'author three';
system(3).No_pages = 100;
arrayfun(@(x) disp(system(x)),[1:numel(system)])
You can also convert your existing cell to stuct array using cell2struct.

Community Treasure Hunt

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

Start Hunting!

Translated by