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

조회 수: 6 (최근 30일)
Meowooo
Meowooo 2017년 10월 13일
답변: Walter Roberson 2017년 10월 14일
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
James Tursa
James Tursa 2017년 10월 13일
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 2017년 10월 13일
I haven't learned this in my class yet, but how could I add up rows then? By directly using sprintf?

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2017년 10월 14일
["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'

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by