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

조회 수: 13 (최근 30일)
Ethan Maxey
Ethan Maxey 2022년 2월 20일
댓글: Image Analyst 2022년 2월 21일
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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by