How can I add all the differents additions to one scalar output?

1 回表示 (過去 30 日間)
Marta Gonzalez
Marta Gonzalez 2020 年 9 月 7 日
コメント済み: KSSV 2020 年 9 月 7 日
Write a function called summit that takes three vectors of the
same length as input arguments (the function does not have to check the format
of the input) and returns a scalar as output. If it is called like this,
a = summit (x,y,z)
then
a = x(1)^2 + y(1)*z(1) + x(2)^2 + y(2)*z(2) + . . . +
x(N)^2 + y(N)*z(N),
where N equals the length of x. This function must not use an array operation,
and it must not use the function sum. Instead, it must instead use a forloop.
  3 件のコメント
Steven Lord
Steven Lord 2020 年 9 月 7 日
This sounds like a homework assignment. If it is, show us the code you've written to try to solve the problem and ask a specific question about where you're having difficulty and we may be able to provide some guidance.
If you aren't sure where to start because you're not familiar with how to write MATLAB code, I suggest you start with the MATLAB Onramp tutorial (https://www.mathworks.com/support/learn-with-matlab-tutorials.html) to quickly learn the essentials of MATLAB.
If you aren't sure where to start because you're not familiar with the mathematics you'll need to solve the problem, I recommend asking your professor and/or teaching assistant for help.
Marta Gonzalez
Marta Gonzalez 2020 年 9 月 7 日
I wrote this code:
function v=vector_algebra(a,b,c)
N=length(a)
for n=1:N
v=a(n)^2+b(n)*c(n)
end
end
So it gives me a vector with the different values that it gets at each index, but how can I get a scalar that is the result of the sum of those values without using the sum function ?

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

回答 (1 件)

KSSV
KSSV 2020 年 9 月 7 日
x = rand(3,1) ;
y = rand(3,1) ;
z = rand(3,1) ;
N = length(x) ;
v = 0 ;
for i = 1:N
v = v+x(i)^2+y(i)*z(i) ;
end
  2 件のコメント
Marta Gonzalez
Marta Gonzalez 2020 年 9 月 7 日
Thanks, I didn't see that, it was such a stupid error
KSSV
KSSV 2020 年 9 月 7 日
Thanks is accepting the answer.

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

カテゴリ

Help Center および File ExchangeGet Started with MATLAB についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by