anyone can help me explain the meaning of the following code?

data = [ 1 100 500; 2 200 600; 3 300 700; 4 400 800 ];
headers = {'ID', 'Population', 'Revenue'};
for i = 1:size(data, 1)
fprintf('%-4d %-12d %-10d\n', data(i, :));
end
1 100 500 2 200 600 3 300 700 4 400 800

4 commentaires

Code by itself has no meaning.
That code takes some numbers, and prints them out in the command window, using formatting. You can infer any meaning you wish from the headers array, which is not actually displayed.
i want to know what is this expression meaning 'i = 1:size(data, 1)'.
Torsten
Torsten le 6 Mai 2024
Modifié(e) : Torsten le 6 Mai 2024
It defines a loop over i where i runs from 1 to the number of rows of the matrix "data" (the "1" in size(data,1) refers to the first dimension of the matrix "data", thus the number of rows).
Since "data" has 4 rows, the loop runs from 1 to 4.
'It defines a loop over i where i runs from 1 to the number of rows of the matrix "data" (the "1" in size(data,1) refers to the first dimension of the matrix "data", thus the number of rows).
Since "data" has 4 rows, the loop runs from 1 to 4.'
Dear Torsten,
Thank you for your explaination.
regards,

Connectez-vous pour commenter.

 Réponse acceptée

the cyclist
the cyclist le 6 Mai 2024
Modifié(e) : the cyclist le 6 Mai 2024
I ran your code here. It seems pretty obvious what it does, right?
You might want to do the free online MATLAB Onramp tutorial, if you don't know what a for loop does. You could also read the documentation page for fprintf.
Perhaps the only tricky part is the exact explanation of the formatting strings such as
'%-4d'
That is explained in that documentation page, in the formatSpec section.

Plus de réponses (0)

Catégories

Community Treasure Hunt

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

Start Hunting!

Translated by