필터 지우기
필터 지우기

Generate the output as a cell array using for-loops

조회 수: 2 (최근 30일)
amateurintraining
amateurintraining 2017년 10월 10일
댓글: Guillaume 2017년 10월 10일
I have a function:
function [ squaresCell ] = generateSquares( a,b )
%GENERATESQUARES
% a, b are two integers where a<b
% squaresCell: a two-dimensional cell array that contains the character
% arrays 'x=[x]' and 'x squared=[x^2]' in the first and second columns,
% respectively, for every value a=<x=<b.
for x=(a:b)
squaresCell={'x=[x]','x squared=[x^2]'};
end
But when running the following command, I get this:
>> generateSquares(3,9)
ans =
1×2 cell array
'x=[x]' 'x squared=[x^2]'
How do I get the output to show the values of the answer cell array, such that the answer responds:
>> 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
  댓글 수: 1
Guillaume
Guillaume 2017년 10월 10일
Note:
for someindex = ...
something_that_does_not_depend_on_the_index = ...
end
just repeatedly overwrite the something_that_does_not_depend_on_the_index which, when the loop is finished, will just contain the value computed on the last iteration.

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

채택된 답변

Guillaume
Guillaume 2017년 10월 10일
Where have you seen that matlab would replace the text [something] by the value of the something variable? If you invent your own syntax, it's no wonder that it doesn't work.
Probably the simplest:
function squaresCell = generateSquares( a,b)
squaresCell = [compose('x = %d', (a:b).'), compose('x squared = %d', ((a:b).^2).']);
end

추가 답변 (0개)

카테고리

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