Confused about function syntax. Need to create my own function.
13 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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
0 Commenti
Risposte (1)
Image Analyst
il 20 Feb 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 Commenti
Image Analyst
il 21 Feb 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.
Vedere anche
Categorie
Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!