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

1 次查看(过去 30 天)
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?

回答(2 个)

Stephen23
Stephen23 2018-4-25
编辑:Stephen23 2018-4-25
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 2018-4-25
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