Confused about function syntax. Need to create my own function.

4 次查看(过去 30 天)
My task is as follows: Write a script that determines if the set of three vectors {v1, v2, v3} is linearly independent. If so, it prints “linearly independent” on the screen. Otherwise, it computes and prints on the screen weights c1, c2 such that v3 = c1v1 + c2v2:
This is what I've got so far. The trouble is in the Else condition. I'm unsure how to solve for c1 or c2 giving the vector equation above.
A = [3,0,6;-1,1,-3.5;4,5,0.5];
[~,p] = rref(A);
if setdiff(1:size(A,2),p) == 0
disp('linearly independent')
else
%prints on the screen weights c1, c2 such that v3 = c1v1 + c2v2:
function [c1,c2] = myFun(v1,v2,v3)
v1 = A(:, 1);
v2 = A(:, 2);
v3 = A(:, 3);
c1=(v3-c2v2)/(v1);
c2=(v3-c1v1)/(v2);
end

回答(1 个)

Image Analyst
Image Analyst 2022-2-20
You need to define the function AFTER your script, not within an "else" block.
A = [3,0,6;-1,1,-3.5;4,5,0.5];
% Call the function with this A:
[c1,c2] = myFun(A)
% Rest of code follows... (I didn't check it).
[~,p] = rref(A);
if setdiff(1:size(A,2),p) == 0
disp('linearly independent')
else
%prints on the screen weights c1, c2 such that v3 = c1v1 + c2v2:
end
% Now call the function [c1, c2] = myFun(A) somewhere above in that code.
%========================================================================
function [c1, c2] = myFun(A)
v1 = A(:, 1);
v2 = A(:, 2);
v3 = A(:, 3);
c1 = (v3 - c2v2) / v1;
c2 = (v3 - c1v1) / v2;
end
  4 个评论
Ethan Maxey
Ethan Maxey 2022-2-21
What my code does is in the original question,
I am trying to solve for c1 and c2, given v3 = c1v2 + c2v2
function [c1, c2] = myFun(A)
v1 = A(:, 1);
v2 = A(:, 2);
v3 = A(:, 3);
c1 = (v3 - c2v2) / v1;
c2 = (v3 - c1v1) / v2;
end
Image Analyst
Image Analyst 2022-2-21
I assume you mean v3 = c1v1 + c2v2
So isn't it
c = v3 / [v1, v2]
or maybe it's
c = v3 \ [v1, v2]
Make sure those vectors are column vectors, not row vectors. I'm not sure which direction the slash is off the top of my head and my MATLAB is totally tied up now doing an hours long deep learning training.

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by