Selecting different element of a matrix with each function operation

7 ビュー (過去 30 日間)
JD
JD 2018 年 4 月 30 日
コメント済み: sloppydisk 2018 年 4 月 30 日
Hi guys,
Say I have a two column 5x2 matrix A (defined as a global variable) with 0,1,2,3,4 in the first column and 2,4,6,8,10 in the second column. Say I also have a function in a separate function file that goes something like this:
function y = func(x)
global A;
y = x - A(p,n)
end
In my main Matlab file (where A is), I've set up a 'while' loop whereby func(x) continuously operates for a total of 5 times.
So my question/problem is this: for each operation of func(x), is it possible to select a different element of the matrix A. For example, for the first func(x) operation, I want it to carry out y = x - A(1,2); for the second func(x) operation, I want it to carry out y = x - A(2,2), and so on until the fifth func(x) operation completes.
Hopefully this is somewhat understandable - I've 'created' the above problem as an example designed to highlight the specific issue I'm trying to tackle, so it might not work/make sense as a whole.
Any help is greatly appreciated.

採用された回答

sloppydisk
sloppydisk 2018 年 4 月 30 日
Hi JD,
You could pass a counter variable i to your function as such:
i = 1;
while condition
i = i+1;
end
function y = func(x, i)
global A;
y = x - A(i,2);
end
  2 件のコメント
JD
JD 2018 年 4 月 30 日
that seems to have done it - thank you very much!
sloppydisk
sloppydisk 2018 年 4 月 30 日
Lovely! <3

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeR Language についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by