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

12 vues (au cours des 30 derniers jours)
Ethan Maxey
Ethan Maxey le 20 Fév 2022
Commenté : Image Analyst le 21 Fév 2022
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

Réponses (1)

Image Analyst
Image Analyst le 20 Fév 2022
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 commentaires
Ethan Maxey
Ethan Maxey le 21 Fév 2022
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 le 21 Fév 2022
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.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Creating and Concatenating Matrices dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by