create indexes of x in a for loop

Hi all, I am trying to create and save some x values in an array in a format of A=[x(2)+x(3);x(3)+x(6);x(4)+x(9)];
so I tried something like that
for i=1:3
y=@(x) x(i+1)+x(3*i);
end
however I get for each i the same expression,
y=@(x)x(i+1)+x(3*i)
Is there any way to do that?
thanks
Nikolas

Answers (1)

Stephen23
Stephen23 on 14 Nov 2018
Edited: Stephen23 on 14 Nov 2018
It is not very clear what you are trying to achieve, but it is possible to store a function handle in a cell array:
C = cell(1,3);
for k=1:3
C{k} = @(x) x(k+1)+x(3*k);
end
Although to be honest it is not clear why you are defining a function handle at all. If x is already defined, why not just get the numeric values directly:
N = nan(1,3);
for k=1:3
N(k) = x(k+1)+x(3*k);
end

9 Comments

Hi again ,
thanks for the reply. I tried this but it still put the values with i, and not something like
A=[x(2)+x(3);x(3)+x(6);x(4)+x(9)]
well it's a long story why I am trying to do this keeping the x, it's because I am trying to create a for loop to create my objective function.
thanks again
Stephen23
Stephen23 on 14 Nov 2018
Edited: Stephen23 on 14 Nov 2018
It is not clear why you need a loop. Simple indexing would probably give what you are looknig for:
V = 1:3
A = x(V) + x(3*V)
A = A(:)
thanks for the prompt reply,
I am getting an error:
"Index exceeds array bounds."
thanks
"I am getting an error:"
Index exceeds array bounds
Then you are trying to access an element of x that does not exist.
Solution: do not try to access elements of x that do not exist.
well that's parft of the question,
if there is any way of indexing a variable x which value is not known.
thanks
Nikolas
"if there is any way of indexing a variable x which value is not known."
Of course it is possible to index a variable whos value is not known:
>> A = rand(4,4); % random matrix whos values I don't know
>> A(2,3) % index into it
ans = 0.77218
Now we know that value!
But it stands to reaon that you cannot retrieve the value of an element that does not exist.
I get the feeling that you don't want indexing, but perhaps you are trying to create a function of x. It would help if you explain a little about what you are actually trying to achieve here.
thanks for the answer again,
anyway my problem if there is any way to do symbolic indexing
for example
A=[ x(1)+x(2) ; X(3)+x(4)]
maybe my question is not very clear
Nikolas
"anyway my problem if there is any way to do symbolic indexing"
What exactly is "symbolic indexing"?
Perhaps a simple function of x is what you are looking for... nothing to do with indexing at all.
well my problem is, if I have a symbolic variable x,
is it possible to create somehow something like
A=[ x(1)+x(2) ; X(3)+x(4)] etc.
by using an index i for example?

Sign in to comment.

Tags

Community Treasure Hunt

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

Start Hunting!