Use for-loops to create a function with the following header (2D cell arrary)
    5 views (last 30 days)
  
       Show older comments
    
Use for-loops to create a function with the following header:
function [ squaresCell ] = generateSquares ( a, b )
where: a, b are two integers where a < b and squaresCell is a two-dimensional cell array that contains the character arrays ‘x = [x]’ and ‘x squared = [x2]’ in the first and second columns, respectively, for every value a ≤ x ≤ b. Your function should be able to reproduce the following test case:
>> generateSquares (3 ,9)
ans =
7x2 cell array
‘x = 3’ ‘x squared = 9 ’
‘x = 4’ ‘x squared = 16 ’
‘x = 5’ ‘x squared = 25 ’
‘x = 6’ ‘x squared = 36 ’
‘x = 7’ ‘x squared = 49 ’
‘x = 8’ ‘x squared = 64 ’
‘x = 9’ ‘x squared = 81 ’
My answer:
function [ squaresCell ] = generateSquares(a,b)
for x = random(a,b)
    a = {'x = [x]' 'x squared = [(x).^2]'}; 
    a(end+(b-a),:) = {'x = [x+(b-a)','[x+(b-a).^2]'};
end
squaresCell = {'x = [x]' 'x squared = [(x).^2]'};
end
What was my problem? Thanks a lot!!!
2 Comments
  James Tursa
      
      
 on 13 Oct 2017
				Hint: Consider using the sprintf function. E.g.,
>> a = 5;
>> c{1,1} = sprintf('The value of x is %d',a)
c = 
    'The value of x is 5'
>> c{1,2} = sprintf('The value of x^2 is %d',a^2)
c = 
    'The value of x is 5'    'The value of x^2 is 25'
Answers (1)
  Walter Roberson
      
      
 on 14 Oct 2017
        According to https://www.mathworks.com/matlabcentral/answers/361260-for-loop-question-switch-loop-question-don-t-know-how-to-incorporate-them-together you have learned to use strings. So use strings.
["abc = " + (1:5).', "pqr = " + (8:12).']
Now you just have to find a way to convert the string array to a cell array of character vectors... perhaps the documentation of string operations will have something you could use.
There is one trick here: you will need to disp() the cell array, not just allow it to be displayed. Notice the difference in displayed output:
>> zzz
zzz =
  5×2 cell array
    {'abc = 1'}    {'pqr = 8' }
    {'abc = 2'}    {'pqr = 9' }
    {'abc = 3'}    {'pqr = 10'}
    {'abc = 4'}    {'pqr = 11'}
    {'abc = 5'}    {'pqr = 12'}
>> disp(zzz)
    'abc = 1'    'pqr = 8' 
    'abc = 2'    'pqr = 9' 
    'abc = 3'    'pqr = 10'
    'abc = 4'    'pqr = 11'
    'abc = 5'    'pqr = 12'
0 Comments
See Also
Categories
				Find more on Loops and Conditional Statements in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!

