Azzera filtri
Azzera filtri

Use for-loops to create a function with the following header (2D cell arrary)

2 visualizzazioni (ultimi 30 giorni)
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 Commenti
James Tursa
James Tursa il 13 Ott 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'
Meowooo
Meowooo il 13 Ott 2017
I haven't learned this in my class yet, but how could I add up rows then? By directly using sprintf?

Accedi per commentare.

Risposte (1)

Walter Roberson
Walter Roberson il 14 Ott 2017
["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'

Categorie

Scopri di più su Cell Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by