I need some help with understanding the '2' close to the second d
    4 vues (au cours des 30 derniers jours)
  
       Afficher commentaires plus anciens
    
    Reuben Addison
 le 13 Jan 2019
  
    
    
    
    
    Modifié(e) : madhan ravi
      
      
 le 15 Jan 2019
            Hello, still in the learning phase of my matlab journey
a = [1 2 3 4 5]
asq = a.*a
for i =1:5
fprintf ('The square of %d is 2d\n', a(i), asq(i))
end
0 commentaires
Réponse acceptée
  madhan ravi
      
      
 le 13 Jan 2019
        
      Modifié(e) : madhan ravi
      
      
 le 15 Jan 2019
  
      https://www.mathworks.com/help/matlab/ref/fprintf.html#btf8xsy-1_sep_shared-formatSpec - it's used for printing values see the link for better understanding , your missing % in front. Also have a look at https://www.mathworks.com/help/matlab/ref/sprintf.html#btf_b35  
fprintf ('The square of %d is %2d\n', a(i), asq(i)) % edited after steven's comment loop can be avoided 
                               ^---denotes space to the right 
4 commentaires
  Stephen23
      
      
 le 13 Jan 2019
				
      Modifié(e) : Stephen23
      
      
 le 13 Jan 2019
  
			@madhna ravi: how did you actually test your answer?:
>> fprintf ('The square of %d is %2d\n', a.', asq.')
The square of 1 is  2
The square of 3 is  4
The square of 5 is  1
The square of 4 is  9
The square of 16 is 25
Since when does 16 squared give 25 ? Or 4 squared give 9 ?
See my answer for the correct, tested  solution.
  madhan ravi
      
      
 le 13 Jan 2019
				Yes but then I thought I changed it but then you posted it as an answer thank you though for reminding.
Plus de réponses (1)
  Stephen23
      
      
 le 13 Jan 2019
        
      Modifié(e) : Stephen23
      
      
 le 13 Jan 2019
  
      >> fprintf ('The square of %d is %2d\n', [a;asq])
The square of 1 is  1
The square of 2 is  4
The square of 3 is  9
The square of 4 is 16
The square of 5 is 25
The reason is simple: MATLAB operates down the columns first, so by creating this matrix
>> [a;asq]
ans =
    1    2    3    4    5
    1    4    9   16   25
the fprintf will process them in order 1, 1, 2, 4, 3, 9, 4, 16, 5, 25. And each consecutive pair of those gets printed by that format string, because it specifies two number formats.
0 commentaires
Voir également
Catégories
				En savoir plus sur Multidimensional Arrays dans Help Center et File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


