How can i define with variable

COORD = [0 0;2 0;4 0;2 2;0 2];
CON = [2 1;3 2;3 4;2 4;4 1;4 5];
for a = 1:6
i = CON(a,1);
j = CON(a,2);
COORD(j,1);
COORD(i,1);
dx = COORD(j,1)-COORD(i,1);
dy = COORD(j,2)-COORD(i,2);
lambdax(a) = dx ;
lambday(a) = dy ;
end
for a = 1:6
K = [lambdax(a)^2 lambdax(a)*lambday(a) -lambdax(a)^2 -lambdax(a)*lambday(a);lambdax(a)*lambday(a) lambday(a)^2 -lambdax(a)*lambday(a) -lambday(a)^2;-lambdax(a)^2 -lambdax(a)*lambday(a) lambdax(a)^2 lambdax(a)*lambday(a);-lambdax(a)*lambday(a) -lambday(a)^2 lambdax(a)*lambday(a) lambday(a)^2]
end
Hello everyone, this is my script it is working now but i need K in the form of K(a) or K(b), if i write K(a) it is not working. How can i write like K(a)?

 Accepted Answer

I still do not understand what you want to do, however it is straightforward to create ‘K’ as an anonymous function:
K = @(a) [lambdax(a).^2 lambdax(a)*lambday(a) -lambdax(a).^2 -lambdax(a).*lambday(a);lambdax(a).*lambday(a) lambday(a).^2 -lambdax(a).*lambday(a) -lambday(a).^2;-lambdax(a).^2 -lambdax(a).*lambday(a) lambdax(a).^2 lambdax(a).*lambday(a);-lambdax(a).*lambday(a) -lambday(a).^2 lambdax(a).*lambday(a) lambday(a).^2];
That should then produce whatever it is that you want from calling ‘K’ as a function.
See the documentation section on Anonymous Functions for details on how they work and how to use them.
I also vectorised ‘K’. See Array vs. Matrix Operations for those details.
.

6 Comments

In my script there is 6 K but it defined last one to K, i want that i ve K(1),K(2)...K(6)
In my script there is 6 K but it defined last one to K, i want that i ve K(1),K(2)...K(6)
I have absolutely no idea what that means.
I cannot go further without knowing what ‘lambdax’ and ‘lambday’ are. They need to be defined, regardless of whether they are functions or arrays.
fatih ayça
fatih ayça on 6 Mar 2021
Edited: fatih ayça on 6 Mar 2021
I editted again,lambdax and lambday has 6 different values. So there are 6 value for K, but this script define last one for K, i want call K with 6 different value. Sorry for my bad english.
It would be easiest to define ‘K’ as a cell array in the loop:
K{a} = [lambdax(a).^2 lambdax(a).*lambday(a) -lambdax(a).^2 -lambdax(a).*lambday(a);lambdax(a).*lambday(a) lambday(a).^2 -lambdax(a).*lambday(a) -lambday(a).^2;-lambdax(a).^2 -lambdax(a).*lambday(a) lambdax(a).^2 lambdax(a).*lambday(a);-lambdax(a).*lambday(a) -lambday(a).^2 lambdax(a).*lambday(a) lambday(a).^2];
Then to get the values for ‘K{1}’ for example:
K1 = K{1}
producing:
K1 =
4 0 -4 0
0 0 0 0
-4 0 4 0
0 0 0 0
and so for the rest.
Thank you so much.
As always, my pleasure!

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!