You are now following this question
- You will see updates in your followed content feed.
- You may receive emails, depending on your communication preferences.
Plug in matrix values into a Formula
7 views (last 30 days)
Show older comments
Hi, can some one help me with the following:
I have matrix U and X
U=[-1.5 -1.0 -.5 0]; X = [1.5 0 0 0 0];
I want to substitute all the values of Big X and Big U into small x and u in following equation:
syms x u; X_E=x^2+*u
and i want my results to be in a matrix form. I was doing the following; however i want to find out a more efficient way to do it
X_Next=[subs(X_E,[x u],[X(1,1) U(1,1)]); subs(X_E,[x u],[X(1,1) U(1,2)]) ;subs(X_E,[x u],[X(1,1) U(1,3)]) ;subs(X_E,[x u],[X(1,1) U(1,4)])]
Thanks a lot in advance.
3 Comments
dpb
on 22 May 2014
X_E=X.^2+U; % unless I'm missing something don't need symbolics here
If want to change values of X and U and reevaluate, use anonymous function--
>> x=rand(2); % some values
>> u=randn(2);
>> f=@(X,U) X.^2+U; % the functional form
f =
@(X,U)X.^2+U
>> f(x,u)
ans =
0.0109 -0.4297
0.1324 1.7811
>> u=-u;
>> f(x,u)
ans =
0.8484 1.9189
1.0877 -0.5476
>>
Observe changing the value in the u-array and reevaluating changed the results of the function.
Fredy
on 22 May 2014
Edited: Fredy
on 22 May 2014
How about if lets say my X matrix is [1 2 3 4 5 6] and U is [1 2] and i want to calculate
F(x,u)=F(1,1)
=F(1,2)
=F(2,1)
=F(2,2)
=F(3,1)
=F(3,2) etc.
and display it as a Vector(x rows and u columns)
Accepted Answer
dpb
on 22 May 2014
Edited: dpb
on 22 May 2014
>> x=1:6;u=1:2;
>> [X,U]=meshgrid(x,u); % make commensurate sizes...
>> f(X(:),U(:)) % evaluate vectors
ans =
2
3
5
6
10
11
17
18
26
27
37
38
>>
5 Comments
Fredy
on 22 May 2014
I should have been more clear, What I am trying to do is the following
Lets say your function is f = X.^2+U; and i want to evaluate that function with all given values for X[1 2 3 4 5 6] and U[1 2] Ex: the first answer would be F(1 1) = 1^2+ 1
Second answer would be F(1 2) = 1^2+ 2 Third answer would be F(2 1) = 2^2+1 etc...
Thank you so much
dpb
on 22 May 2014
Edited: dpb
on 22 May 2014
We defined the function handle f earlier, remember????
>> f=@(X,U) X.^2+U; % the functional form
f =
@(X,U)X.^2+U
Now we've just evaluated it with a different set of inputs.
Try the above without the (:) on the two arrays to make a vector and see what happens. Also look in detail at the output of meshgrid call and check the doc's on how that works.
Fredy
on 26 May 2014
Edited: Fredy
on 26 May 2014
(Note: i attached the question in a .txt document since the format here does not look very organize)
Could you please look at the attach document. What you see in the tables is what I am trying to do with matlab. So far with your help I am able to come up with all columns except the last two since i do not know how to get the minima of a matrix in a 5 row interval. Do you think i am using the right approach? Here is my code so far.
u=[1 0.5 0 -0.5 -1]; %Given u x = [1.5 1 0.5]; %Given x X_K_1=@(X,U)X+U; %Next State of X(K+1) [X,U]=meshgrid(x,u); % X_LAST=[X_K_1(X(:),U(:))]; % Plugs in all values of x and u into X_K_1
F_1=input('Please enter a value for X: ') % User input is X_LAST.^2 U_1=input('Please enter a value for U: ') %User input is 2.*U.^2
J_2_1=@(X_LAST,U_1)F_1+U_1; %Formula for J_2_1 in terms of F_1 and U_1 function
J_COST=[J_2_1(X_LAST(:),U(:))] % Cost for all values of x and u in formula J_2_1
IF you run this, i Get the following Result: J_COST =
8.2500
4.5000
2.2500
1.5000
2.2500
6.0000
2.7500
1.0000
0.7500
2.0000
4.2500
1.5000
0.2500
0.5000
2.2500
Now, here where I am a bit lost on how i go about selecting the minima of every 5 rows. For example the first minima is from : [ 8.2500 4.5000 2.2500 1.5000 2.2500] which is 1.5.
The next minima will be from row 6 to 10. Etc...
Thank you so much for all your help!
More Answers (3)
dpb
on 27 May 2014
Edited: dpb
on 27 May 2014
...how i go about selecting the minima of every 5 rows...
OK, here is where you need to think (and it helps when you get to where you dream in :) ) Matlab--
>> min(reshape(J_COST,5,[])).'
ans =
1.5000
0.7500
0.2500
>>
I'll let you think on that a while... :) HINT: "memory storage order"
7 Comments
Fredy
on 27 May 2014
WoW, that is AWESOME!
Those values were the results of some values OF
u=[1 0.5 0 -0.5 -1]; GIVEN
x = [1.5 1 0.5]; %Given
in the formula
J_2_1=@(X_LAST,U_1)F_1+U_1;
J_COST=[J_2_1(X_LAST(:),U(:))]
Visually is easy to determine which value of 'u' was used to come up with a minima, is there a function in matlab that could track back and see which value of 'u' was used?
Thanks a lot again! :):)
dpb
on 27 May 2014
Of course...
>> [mn,imn]=min(reshape(J_COST,5,[]))
mn =
1.5000 0.7500 0.2500
imn =
4 4 3
>> u=[1 0.5 0 -0.5 -1];
>> u(imn)
ans =
-0.5000 -0.5000 0
>> u(imn)
It will venture to suggest you dig into the doc's more in detail looking at the optional returns and the details of the functions as you use them and then really think about whether one or more of those extras might just help...altho you have gotten quite a long way from the one exposition on anonymous functions we started of with, it seems, so kudos on that, and sometimes it's not so obvious.
Do you follow the primary "trick" here, though? It's important both for the immediate problem and in being a key to many Matlab solutions.
Fredy
on 27 May 2014
I am sorry , i do not know what you mean by primary trick. I understand what I am trying to get at, and ive never used matlab before. I am sure that there are other Matlab solutions but at this point I am just trying to come up with one that works :/
You have been really helpful, I spend some time reading a matlab book that i bought but it does not go over all the fuctions. Without your help i would be still reading with no progress...
Fredy
on 27 May 2014
I believe i understand it,
[mn,imn]=min(reshape(J_COST,5,[]))
Is basically reshaping J_COST by a new matrix that has J_COST minimun in every 5 rows, and also there is the imn matrix that has the location of 'u' where there is a J_COST minimum.
dpb
on 27 May 2014
...reshaping J_COST by a new matrix that has J_COST minimun in every 5 rows,
Close, but not, precisely, no...read from the inside out and if needed look at the result of the intermediary steps to see what's happening. As mentioned before, the "how" is significant piece of understanding that will prove to be invaluable going forward in using Matlab. As said before, it's tied into internal storage order in Matlab which is "column major".
Fredy
on 27 May 2014
Thx a lot again dpb, I was able to construct my first table, now i would like to know if its possible to create a Matrix which Looks at matrix Z and scans my State column and once it finds the value equal(or nearest) to my State column of,it will select its corresponding OptimalJ. Also if Z is greater than any value of my state column it will as
For example: for my first value of Z which is 2.5, since its out of range from my state column i want to put a large number maybe 10000 or a blank space that still exist in my matrix. The fourth value of Z is 1.0, so i would like to select 0.75 from my OptimalJ.
T =
State OptimalJ OptimalU
_____ ________ ________
1.5 1.5 -0.5
1 0.75 -0.5
0.5 0.25 0
>> Z =
2.5000
2.0000
1.5000
1.0000
0.5000
2.0000
1.5000
1.0000
0.5000
0
1.5000
1.0000
0.5000
0
-0.5000
so the result will look something like this =
x------------------>blank or large number 1000(
x-----------------> since i will be finding minimuns again.
1.5000
0.7500
0.2500 ....etc
I was playing with find function but i had no success, thanks a lot again!!
dpb
on 27 May 2014
interp1(T(:,1),T(:,2),Z,'nearest',NaN)
20 Comments
Fredy
on 28 May 2014
Thanks dpb, i tried running that and
I get this error when running that code:
interp1(T(:,1),T(:,2),X_LAST,'nearest',NaN)
Error using interp1 (line 108)
X must be a vector of numeric coordinates.
When i checked what X is it shows the following:
X =
1.5000 1.0000 0.5000
1.5000 1.0000 0.5000
1.5000 1.0000 0.5000
1.5000 1.0000 0.5000
1.5000 1.0000 0.5000
when i checked line 108 i see the following:
if ndataarg == 2
V = varargin{1};
if isvector(V)
orig_size_v = size(V);
V = V(:); % Reorient not considered a resize
else
orig_size_v = size(V);
n = orig_size_v(1);
ds = orig_size_v(2:end);
prodDs = prod(ds);
V = reshape(V,[n prodDs]);
end
Xq = varargin{2};
X =(1:size(V,1))';
elseif ndataarg == 3
X = varargin{1};
if ~isnumeric(X)
error(message('MATLAB:interp1:Xnumeric'));
end
Thank you once again!
dpb
on 28 May 2014
T(:,1) and T(:,2) have to be the numeric vector you showed--can't have any non-numeric stuff hanging around. "X" in the error is referring to the argument "X" in the documentation.
>> T
T =
1.5000 1.5000
1.0000 0.7500
0.5000 0.2500
>> Z
Z =
2.5000 2.0000 1.5000 1.0000 0.5000
>> interp1(T(:,1),T(:,2),Z,'nearest',nan)
ans =
NaN NaN 1.5000 0.7500 0.2500
>>
Fredy
on 28 May 2014
Edited: Fredy
on 28 May 2014
Hi dpb thanks again for quick response...i believe I do understand logical addressing, lets say a = [1.1, 2.1, 3.2, 4.5];
>> B = find(a >= 2 & a < = 4); %B will find values that are in 2<=a<=4
>> a(B) ans = 2.1 3.2
However i want to keep the same matrix dimension, so instead of getting 2.1 3.2 i would like to see [nan 2.1 3.2 nan]
Which topic do you recommend me reading so i could understand it and figure it out?
Thank you!!!
dpb
on 28 May 2014
Edited: dpb
on 28 May 2014
Which topic do you recommend me reading...
You can write the original question as a one-liner...altho I use a "helper function" for the purpose as "syntactic sugar". It is given as
function flg=iswithin(x,lo,hi)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=lo) & (x<=hi);
I'll leave you to ponder on how to use it... :)
NB: I have a "utilities" subdirectory that contains a bunch of these little snippets for a variety of such purposes. Akin to this one is isbetween that is identical except it uses a non-inclusive bounds. There's another version that's general that includes optional flag variables to allow for setting each limit individually as in- or ex-clusive.
NB: as you have written your find above, note that you have found the locations in a that you want to retain, not those that you wished to modify. How do you need to rearrange the logic test (or modify the present test result) to get the locations to change?
Also, the key point I'm trying to teach is that you don't need find here. Although it works to solve the problem for this type of exercise (which is a very common type) it's overkill.
Fredy
on 29 May 2014
When i tried to run the helper function function flg=iswithin(x,lo,hi) i get the following error
Error: Function definitions are not permitted in this context.
What i understand about this function is that it will basically return values with in your lo and hi inputs.
I still do not see how i could use this function to do the following operation
A=[2,1;3,4];
>> B=[1,2;-5,-4];
>> A+B % WITH following boundary condition -1<=ans<=2
ans =
2 nan
nan 0
Would it look something like:
C=[A+B] function flg=iswithin(C,-1,2)
% returns T for values within range of input
% SYNTAX:
% [log] = iswithin(x,lo,hi)
% returns T for x between lo and hi values, inclusive
flg= (x>=-1) & (x<=2);
Thank you Is iswithin a costume function that you have created or is it within matlab?
Thank you
dpb
on 29 May 2014
Edited: dpb
on 29 May 2014
Yes, it's a user-written function -- like any other, put it in an m-file of the same name and invoke as any other as well. You can not put function definitions in a script file or at the command line. The m-file must be located in a directory on matlabpath to be found, of course.
Read up on the section on programming scripts and functions and the difference between...
ADDENDUM:
Then, once you've accomplished that, we're back to the previous point of "how to use it". It's still tied to the object lesson in logical addressing I've been harping on. The BIG HINT is that you do not need any temporary variables in this kind of operation; it can be done as a one-liner.
Again, reread the doc page I posted a link to a couple comments ago--it's got the detail. If that still doesn't get you home, post again and I'll then give out the secret...but I'd really feel like accomplished more if you worked it out on your own... :)
Fredy
on 29 May 2014
After reading that link i came up with this:
A=magic(3)
B=magic(3)
C=(A+B),L=(A+B)<9 & (A+B)>4,C(L)=0
C =
16 2 12
0 10 14
0 18 4
Was is this what you are trying to teach me? How would i go about replacing those zeros with NaN value?
Thanks again for all your help!
dpb
on 29 May 2014
Edited: dpb
on 30 May 2014
Again, you're not taking the generalization to its logical (so to speak :) ) conclusion. I'm pretty sure there's an example there w/ no intermediaries, too, but I didn't go look right now...
Where I've been trying to get you to is something like...
C(C==0)=nan;
Your previous of a range--
C(~iswithin(C,14,18))=nan;
IOW, getting you to realize that unless you need the actual indices for some other reason, you don't need find and the result of a logical test is a logical array that is just as valid as an indexing expression as an intermediary variable storing that result...both, like the memory rearrangement we did some time ago to compute averages over even subsets of an array, are key points in effective use of Matlab.
Fredy
on 30 May 2014
Thanks a lot for all your help,with your help i have gotten the main structure of my code, now i will like to create a repetitive process.
for example
C=
1.0000 1.4000 -0.4000 %KNOWN MATRIX
0.5000 0.1000 -0.4000
0 0 0
B=
8 1 6
3 5 7
4 9 2
C=[interp1(A(:,1),A(:,2),Z,'nearest',NaN)] WHERE Z IS ANOTHER MATRIX
D=[B+C]
[mn,imn]=min(reshape(D,5,[]));
E=(transpose([x;mn;u(imn)]))
I am trying to create this sequence in a loop from here to N stages (%SUMMATION FROM K=0 TO N-1)
so the next stage will be
C_1= [interp1(E(:,1),E(:,2),Z,'nearest',NaN)]
D_1=[C_1+C]
[mn,imn]=min(reshape(D_1,5,[]));
E_1=(transpose([x;mn;u(imn)]))
Next stage will be
c_2= [interp1(E_1(:,1),E_1(:,2),Z,'nearest',NaN)]
D_2=[C_2+C]
[mn,imn]=min(reshape(D_2,5,[]));
E_2=(transpose([x;mn;u(imn)]))
Is it possible i could create this with a simple loop?
Thank you again!
Fredy
on 30 May 2014
Edited: Fredy
on 30 May 2014
Thanks for your quick response dpb!
and Yes, x and u are two vectors that are invariant.
X_B1=input('Enter first boundry of X: ')
X_B2=input('Enter Second boundry of X: ');
X_Q=input('Enter Quantazise values of X: ');
x=linspace(X_B1,X_B2,X_Q)
U_B1=input('Enter first boundry of U: ')
U_B2=input('Enter Second boundry of U: ');
U_Q=input('Enter Quantazise values of U: ');
u=linspace(U_B1,U_B2,U_Q)
The final Result will be all E_1, E_2,E_3.....E_N-1
The quitting criteria will be N-1
N represents the numbers of states, and since the first value of N i have
already calculated i do not need to include it in the loop.
At the end I will be putting the results on a table
State=E_1(:,1);
OptimalJ=E_1(:,2);
OptimalU=E_1(:,3);
T_1=table(State,OptimalJ,OptimalU)
Thank you for your quick response.
dpb
on 31 May 2014
Edited: dpb
on 31 May 2014
Let's just have one complete set of sample inputs and desired output...looks to me like the end result should end up being derivable unless there's something I don't see...but, there's not a fully consistent single place that has all the inputs for a given case afaict. There's no A above, for example, so, let's just get a clean go at it. Also, are there restrictions on sizes--the hardcoded "5" in the reshape operation will fail if there's not a multiple so have to be some limits somewhere...
And, your example above defines a C 2D array then replaces it immediately w/
C=[interp1(A(:,1),A(:,2),Z,'nearest',NaN)];
D=[B+C];
Whassup w/ that??? In this case you don't need the original C and as noted, unless Z is 3x3, the result of C above won't be commensurate in size with B to make the addition possible and then you've got the problem once get past the that immediately following is the aforementioned problematic
[mn,imn]=min(reshape(D,5,[]));
which crashes in flames because mod(numel(D),5) ~=0
You need a lot more work in defining what it is you're actually trying to do; you can't have worked thru the above even manually to get a single iteration, what more the second or third.
dpb
on 1 Jun 2014
Not enough -- doesn't address any of the problems outlined above.
Give one COMPLETE set of input data and what you expect for output. what your input code looks like is immaterial; need a set of data from which you start and then what you expect as output.
See Also
Categories
Find more on Logical 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!An Error Occurred
Unable to complete the action because of changes made to the page. Reload the page to see its updated state.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom(English)
Asia Pacific
- Australia (English)
- India (English)
- New Zealand (English)
- 中国
- 日本Japanese (日本語)
- 한국Korean (한국어)