Selecting different element of a matrix with each function operation

1 次查看(过去 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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by