How to enter multiple values for a single input in a function

So what I'm trying to do is have a function take in a vector of inputs, and then use them seperately in a function. So the function would be something simple, like adding 1 to every input value, but I want the limit of input values to be practically infinite. So I want to assign the variable x to every component of a vector and add 1 to each component, then at the end I want to obtain the sum of every component in the vector. I don't quite know how else to ask this question, something like
x = [1, 2, 3 . . . .]
answer = sum(x+1)

5 件のコメント

Matt J
Matt J 2020 年 9 月 5 日
編集済み: Matt J 2020 年 9 月 5 日
Haven't you asnwered your own question? It sounds like you want this:
function answer = mysum(x)
answer = sum(x+1);
end
or this,
>> mysum=@(x) sum(x+1);
Brett Baxter
Brett Baxter 2020 年 9 月 5 日
The reason why I asked is because I'm having trouble getting it to then find the sum of the components when I make it more complicated. my current function looks something like this
function answer = myfunction(x)
answer = sum((x+1)^2 * mod(x, 2))
end
So what I'm trying to get matlab to do is then take a vector of some specified string of numbers like
x = [1, 2, 3, 4, 5]
and then plug every single value into the function and then sum up every single result into one number. Going back to the original example, I want the function to do something like 1+1, 2+1, . . . and then add up every single result into a single integer
Matt J
Matt J 2020 年 9 月 5 日
Going back to the original example, I want the function to do something like 1+1, 2+1
But the code you've shown sum(x+1) does do precisely that. What operation is it that you think you can't do this way?
Brett Baxter
Brett Baxter 2020 年 9 月 5 日
I figured it out, I had misplaced some of the '.' to specify that I was multiplying vectors. As well, I just needed to specify that I wanted the sum of the output. So sum(answer) to get it to all add up.
Nasir
Nasir 2023 年 9 月 11 日
can someone tell me about how to enter multiple values in single string
x = [1 2 3 4 5 6 ...............................................1000]

サインインしてコメントする。

回答 (1 件)

Asad (Mehrzad) Khoddam
Asad (Mehrzad) Khoddam 2020 年 9 月 5 日

0 投票

Most Matlab functions are vector based. you should use .^ for vector based ^ and .* for vector based *
So you function line looks like this:
answer = sum((x+1).^2 .* mod(x, 2));
and ./ instead of /

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

製品

リリース

R2020a

質問済み:

2020 年 9 月 5 日

コメント済み:

2023 年 9 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by