use vector as input

7 次查看(过去 30 天)
Vincent Degonda
Vincent Degonda 2021-2-28
I want to give each input of a vector as an argument to my function to recive a list of values that i can then plot (my goal is to plot the time it takes to execute the function for a given n). The problem is, that i only get the output of the first entry of the vector. What did I do wrong?
>> n = [1:1:10];
>> [a,b] = calcEulerSum2 (n)
it returns only calcEulerSum2(1)
function [e, a] = calcEulerSum2(n)
den = 1;
e = 1;
tic
for i = 1 : n
den = den * i;
e = e + 1/den;
end
a = toc;
end
  2 个评论
dpb
dpb 2021-2-28
"What did I do wrong?"
We dunno and have no way to know -- you forgot to show us the code for calcEulerSum2
dpb
dpb 2021-2-28
What do you expect for output and what is the expected input?
I think you aren't using for as documented/wanted here.
Try at the command line to see what you get for:
n=1:3;
for i=1:n, disp(i), end
followed by
for i=n, disp(i), end
and see if that doesn't clear up the mystery.

请先登录,再进行评论。

回答(2 个)

Robert U
Robert U 2021-2-28
Hi Vincent Degonda,
Your for-loop call is not providing what you expected. Your input variable is a vector already. dpb tried to lead you to that. Output in vector form would need an indexing of your output variable.
function [e, a] = calcEulerSum2(n)
den = 1;
e = 1;
tic
for i = n
den = den * i;
e(end+1) = e(end) + 1/den;
end
a = toc;
end
Kind regards,
Robert

Steven Lord
Steven Lord 2021-2-28
So you want to compute the value of e and the time required to compute that value for each element of n? A couple of suggestions:
function [e, a] = calcEulerSum2(n)
den = 1;
e = 1;
Make the variable e an array of ones the same size as n. The documentation page for ones include a couple of examples that you can use as a model.
tic
Before you start timing, you'll need a loop over the elements of the input. Use the numel function that gives the number of elements in an array for this loop.
for whichElement = <you fill this in> % I added this to your code
Continuing on with the code you already wrote:
for i = 1 : n
You don't want to use the whole n array here, just one element. Which element should you use instead of n here? I think you can guess.
den = den * i;
e = e + 1/den;
Since e is now an array here, not just one value, you need to operate on and assign back into a particular element. Which element of e? It should be clear.
By the way, you'll need to adjust how (or more precisely where/when) you initialize den. If the first element of n was 3, what should den be when you start processing the second element of n and what will it actually be?
end
a = toc;
end
Since I added a for loop to your code, you'll need one more end statement. Where should the for loop I added end?

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by