How can I use a vector component from a previously defined vector variable in a function? I do not want to redefine the vector variable inside the function!
X is previously loaded into the script using
load('TrussDesign.mat', 'C', 'Sx', 'Sy', 'X', 'Y', 'L' );
and my function is:
function xcoeff = xcoeff(a,b)
A = X(b) - X(a);
B = Y(b) - Y(a);
r = sqrt((A^2)+(B^2));
d = X(a) - X(b);
xcoeff = d/r;
end
I know I can do:
function xcoeff = xcoeff(a,b)
X = cell2mat(struct2cell(load('TrussDesign.mat','X'))); % X positions of joints
Y = cell2mat(struct2cell(load('TrussDesign.mat','Y'))); % Y positions of joints
A = X(b) - X(a);
B = Y(b) - Y(a);
r = sqrt((A^2)+(B^2));
d = X(a) - X(b);
xcoeff = d/r;
end
but the whole point of this question is seeing if I can avoid that so I don't have to change the code if I choose to load a different file in the beginning of the script.

2 件のコメント

Jan
Jan 2021 年 3 月 24 日
Just a question: cell2mat(struct2cell(load()))? What about:
Data = load(File, 'X');
X = Data.X;
% or
X = getfield(load(File, 'X'), 'X');
Grace Chabbott
Grace Chabbott 2021 年 3 月 24 日
編集済み: Grace Chabbott 2021 年 3 月 24 日
oh awesome! thanks so much. Cleaner than what I was doing before. I am still looking for a way to take the file name out of the function completely ...

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

 採用された回答

Matt J
Matt J 2021 年 3 月 24 日

1 投票

Pass X to the function as an additional input,
function xcoeff = xcoeff(a,b,X)

3 件のコメント

Walter Roberson
Walter Roberson 2021 年 3 月 24 日
https://www.mathworks.com/help/matlab/math/parameterizing-functions.html
Jan
Jan 2021 年 3 月 24 日
This is the clean and efficient solution. Providing variables by magic remote access impedes the debugging, but standard input arguments are neat.
Grace Chabbott
Grace Chabbott 2021 年 3 月 24 日
編集済み: Grace Chabbott 2021 年 3 月 24 日
thank you!
UPDATE: This worked perfectly!

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

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File Exchange で Desktop についてさらに検索

質問済み:

2021 年 3 月 24 日

編集済み:

2021 年 3 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by