How do I capture the output from the "present" function and store it in a string - matlab

In Matlab, I have a IDPOLY object which I wish to "present" and store the resulting text in a text file.
eg if a is an IDPOLY object and I do
>> present(a)
I get
Discrete-time IDPOLY model: A(q)y(t) = B(q)u(t) + e(t)
A(q) = 1 - 1.31 q^-1 + 0.2425 q^-2 - 0.431 q^-3 + 0.4987 q^-4
B1(q) = 0.01357 + 0.04006 q^-1 - 0.04489 q^-2 + 0.007757 q^-3
- 0.1761 q^-4 + 0.06396 q^-5 - 0.2874 q^-6 + 0.3835 q^-7
B2(q) = -0.006397
Estimated using ARX with focus on data set iddata_est_shift
Loss function 0.0617185 and FPE 0.061879
Sampling interval: 0.025
Created: 24-Nov-2010 13:05:10
Last modified: 24-Nov-2010 13:06:56
Does anyone know how to capture this text as I'd like to write it to a text file in a log file. There are no returned arguments from present.

You can try using the diary command.

I've found the evalc() command which does exactly what I need.
evalc
Evaluate MATLAB expression with capture
Syntax
T = evalc(S)
[T, X, Y, Z, ...] = evalc(S)
and pass the expression as a string.

Related

Lsode throwing INTDY-- T (=R1) ILLEGAL and invalid input detected

I have my function:
function [result] = my_func(x,y)
result = y^2*(1-3*x)-3*y;
endfunction
Also, my vector with Ts, my function address and my initial variable x_0
load file_with_ts
# Add my limits as I also want to calculate those
# (all values in file_with_ts are within those limits.)
t_points = [-1, file_with_ts, 2]
myfunc = str2func("my_func")
x_0 = 0.9142
I am trying to execute the following line:
lsode_d1 = lsode(myfunc, x_0, t_points)
And expecting a result, but getting the following error:
INTDY-- T (=R1) ILLEGAL
In above message, R1 = 0.7987082301475D+00
T NOT IN INTERVAL TCUR - HU (= R1) TO TCUR (=R2)
In above, R1 = 0.8091168896311D+00 R2 = 0.8280400838323D+00
LSODE-- TROUBLE FROM INTDY. ITASK = I1, TOUT = R1
In above message, I1 = 1
In above message, R1 = 0.7987082301475D+00
error: lsode: invalid input detected (see printed message)
error: called from
main at line 20 column 10
Also, the variable sizes are:
x_0 -> 1x1
t_points -> 1x153
myfunc -> 1x1
I tried transposing the t_points vector
using #my_func instead of the str2func function
I tried adding multiple variables as the starting point (instead of x_0 I entered [x_0; x_1])
Tried changing my function header from my_func(x, y) to my_func(y, x)
Read the documentation and confirmed that my_func allows x to be a vector and returns a vector (whenever x is a vector).
EDIT: T points is the following 1x153 matrix (with -1 and 2 added to the beggining and the end respectively):
-4.9451e-01
-4.9139e-01
-4.7649e-01
-4.8026e-01
-4.6177e-01
-4.5412e-01
-4.4789e-01
-4.2746e-01
-4.1859e-01
-4.0983e-01
-4.0667e-01
-3.8436e-01
-3.7825e-01
-3.7150e-01
-3.5989e-01
-3.5131e-01
-3.4875e-01
-3.3143e-01
-3.2416e-01
-3.1490e-01
-3.0578e-01
-2.9267e-01
-2.9001e-01
-2.6518e-01
-2.5740e-01
-2.5010e-01
-2.4017e-01
-2.3399e-01
-2.1491e-01
-2.1067e-01
-2.0357e-01
-1.8324e-01
-1.8112e-01
-1.7295e-01
-1.6147e-01
-1.5424e-01
-1.4560e-01
-1.1737e-01
-1.1172e-01
-1.0846e-01
-1.0629e-01
-9.4327e-02
-8.0883e-02
-6.6043e-02
-6.6660e-02
-6.1649e-02
-4.7245e-02
-2.8332e-02
-1.8043e-02
-7.7416e-03
-6.5142e-04
1.0918e-02
1.7619e-02
3.4310e-02
3.3192e-02
5.2275e-02
5.5756e-02
6.8326e-02
8.2764e-02
9.5195e-02
9.4412e-02
1.1630e-01
1.2330e-01
1.2966e-01
1.3902e-01
1.4891e-01
1.5848e-01
1.7012e-01
1.8026e-01
1.9413e-01
2.0763e-01
2.1233e-01
2.1895e-01
2.3313e-01
2.4092e-01
2.4485e-01
2.6475e-01
2.7154e-01
2.8068e-01
2.9258e-01
3.0131e-01
3.0529e-01
3.1919e-01
3.2927e-01
3.3734e-01
3.5841e-01
3.5562e-01
3.6758e-01
3.7644e-01
3.8413e-01
3.9904e-01
4.0863e-01
4.2765e-01
4.2875e-01
4.3468e-01
4.5802e-01
4.6617e-01
4.6885e-01
4.7247e-01
4.8778e-01
4.9922e-01
5.1138e-01
5.1869e-01
5.3222e-01
5.4196e-01
5.4375e-01
5.5526e-01
5.6629e-01
5.7746e-01
5.8840e-01
6.0006e-01
5.9485e-01
6.1771e-01
6.3621e-01
6.3467e-01
6.5467e-01
6.6175e-01
6.6985e-01
6.8091e-01
6.8217e-01
6.9958e-01
7.1802e-01
7.2049e-01
7.3021e-01
7.3633e-01
7.4985e-01
7.6116e-01
7.7213e-01
7.7814e-01
7.8882e-01
8.1012e-01
7.9871e-01
8.3115e-01
8.3169e-01
8.4500e-01
8.4168e-01
8.5705e-01
8.6861e-01
8.8211e-01
8.8165e-01
9.0236e-01
9.0394e-01
9.2033e-01
9.3326e-01
9.4164e-01
9.5541e-01
9.6503e-01
9.6675e-01
9.8129e-01
9.8528e-01
9.9339e-01
Credits to Lutz Lehmann and PierU.
The problem lied in the array t_points not being a monotonous array. Adding a sort(t_points) before doing any calculations fixed the error.

Simulink model 'to workspace' output

I am trying to control motor torque and am using a workspace variable in Simulink and want to output similar variable to workspace.
I have size(T_u)=[3, 91] whereas the output I am getting from the simulation has size [91, 90]
I am unable to understand why this is so.
Code that I am using:
load('Motor_Param.mat')
t = 1:0.1:10;
T_o = [0.05*(10-t);0.04*(10-t);0.03*(10-t)];
T_d = zeros(size(T_o));
T_e = (T_d - T_o);
C_PD = pid(100,0,10,100);
T_u = zeros(size(T_e));
for k=1:size(T_e,1)
T_u(k,:) = lsim(C_PD,T_e(k,:),t);
%T_u(1,:)= -45.0450000000000 -44.5444552724092 -44.0439110892737 -43.5433674500493 -43.0428243541925 -42.5422818011600 -42.0417397904094 -41.5411983213986 -41.0406573935862 -40.5401170064312 -40.0395771593933 -39.5390378519326 -39.0384990835098 -38.5379608535861 -38.0374231616233 -37.5368860070837 -37.0363493894301 -36.5358133081260 -36.0352777626353 -35.5347427524223 -35.0342082769522 -34.5336743356904 -34.0331409281029 -33.5326080536564 -33.0320757118181 -32.5315439020554 -32.0310126238368 -31.5304818766308 -31.0299516599067 -30.5294219731343 -30.0288928157839 -29.5283641873264 -29.0278360872332 -28.5273085149760 -28.0267814700274 -27.5262549518604 -27.0257289599483 -26.5252034937652 -26.0246785527857 -25.5241541364848 -25.0236302443380 -24.5231068758215 -24.0225840304120 -23.5220617075865 -23.0215399068228 -22.5210186275990 -22.0204978693939 -21.5199776316868 -21.0194579139572 -20.5189387156857 -20.0184200363529 -19.5179018754402 -19.0173842324294 -18.5168671068029 -18.0163504980435 -17.5158344056347 -17.0153188290603 -16.5148037678048 -16.0142892213531 -15.5137751891906 -15.0132616708034 -14.5127486656779 -14.0122361733011 -13.5117241931606 -13.0112127247442 -12.5107017675407 -12.0101913210389 -11.5096813847285 -11.0091719580996 -10.5086630406426 -10.0081546318487 -9.50764673120954 -9.00713933821711 -8.50663245236405 -8.00612607314350 -7.50562020004906 -7.00511483257487 -6.50460997021554 -6.00410561246623 -5.50360175882257 -5.00309840878072 -4.50259556183731 -4.00209321748951 -3.50159137523496 -3.00109003457184 -2.50058919499879 -2.00008885601498 -1.49958901712007 -0.999089677814209 -0.498590837598075 0.00190750402718064
a = sim('Motor_Control','SimulationMode','normal');
out = a.get('T_l')
end
Link to .mat and .slx files is: https://drive.google.com/open?id=1kGeA4Cmt8mEeM3ku_C4NtXclVlHsssuw
If you set the Save format in the To Workspace block to Timeseries the output will have the dimensions of the signal times the number of timesteps.
In your case I activated the option Display->Signals & Ports->Signal dimensions and the signal dimensions in your model look like this:
So the signal that you output to the workspace has the size 90. Now if I print size(out.Data) I get
ans = 138 90
where 90 is the signal dimension and 138 is the number of timesteps in your Simulink model.
You could now use the last row of the data (which has the length 90) and add it to your array.
I edit your code, the code has [21,3] output size. "21" is coming from (t_final*1/sample_time+1)
In your code, time t should start from 0.
Motor_Control.slx model has 0.1 sample time if you run the model for a 9 second, the output file has 91 samples for each signal and that's why you have [91, 90] sized output. I download from your drive link and this Simulink model has 2 sec. simulation.
T_u is used as an input of the Simulink model, it is not constant so T_u must be time series.
The edited code is below;
load('Motor_Param.mat')
t = 0:0.1:10;
T_o = [0.05*(10-t);0.04*(10-t);0.03*(10-t)];
T_d = zeros(size(T_o));
T_e = (T_d - T_o);
C_PD = pid(100,0,10,100);
T_u = timeseries(zeros(size(T_e)),t);
for k=1:size(T_e,1)
T_u.Data(k,:) = lsim(C_PD,T_e(k,:),t);
a = sim('Motor_Control','SimulationMode','normal');
out = a.get('T_l')
end

how to read from file and display the data in desired rows in Matlab

I am trying to read from a file and display the data in rows 6, 11, 111 and 127 in Matlab. I could not figure out how to do it. I have been searching Matlab forums and this platform for an answer. I used fscanf, textscan and other functions but they did not work as intended. I also used a for loop but again the output was not what I wanted. I can now only read one row and display it. Simply I want to display all of them(data in rows given above) at the same time. How can I do that?
matlab code
n = [0 :1: 127];
%% Problem 1
figure
x1 = cos(0.17*pi*n)
%it creates file and writes content of x1 to the file
fileID = fopen('file.txt','w');
fprintf(fileID,'%d \n',x1);
fclose(fileID);
%line number can be changed in order to obtain wanted values.
fileID = fopen('file.txt');
line = 6;
C = textscan(fileID,'%s',1,'delimiter','\n', 'headerlines',line-1);
celldisp(C)
fclose(fileID);
and this is the file
1
8.607420e-01
4.817537e-01
-3.141076e-02
-5.358268e-01
-8.910065e-01
-9.980267e-01
-8.270806e-01
-4.257793e-01
9.410831e-02
5.877853e-01
9.177546e-01
9.921147e-01
7.901550e-01
3.681246e-01
-1.564345e-01
-6.374240e-01
-9.408808e-01
-9.822873e-01
-7.501111e-01
-3.090170e-01
2.181432e-01
6.845471e-01
9.602937e-01
9.685832e-01
7.071068e-01
2.486899e-01
-2.789911e-01
-7.289686e-01
-9.759168e-01
-9.510565e-01
-6.613119e-01
-1.873813e-01
3.387379e-01
7.705132e-01
9.876883e-01
9.297765e-01
6.129071e-01
1.253332e-01
-3.971479e-01
-8.090170e-01
-9.955620e-01
-9.048271e-01
-5.620834e-01
-6.279052e-02
4.539905e-01
8.443279e-01
9.995066e-01
8.763067e-01
5.090414e-01
-4.288121e-15
-5.090414e-01
-8.763067e-01
-9.995066e-01
-8.443279e-01
-4.539905e-01
6.279052e-02
5.620834e-01
9.048271e-01
9.955620e-01
8.090170e-01
3.971479e-01
-1.253332e-01
-6.129071e-01
-9.297765e-01
-9.876883e-01
-7.705132e-01
-3.387379e-01
1.873813e-01
6.613119e-01
9.510565e-01
9.759168e-01
7.289686e-01
2.789911e-01
-2.486899e-01
-7.071068e-01
-9.685832e-01
-9.602937e-01
-6.845471e-01
-2.181432e-01
3.090170e-01
7.501111e-01
9.822873e-01
9.408808e-01
6.374240e-01
1.564345e-01
-3.681246e-01
-7.901550e-01
-9.921147e-01
-9.177546e-01
-5.877853e-01
-9.410831e-02
4.257793e-01
8.270806e-01
9.980267e-01
8.910065e-01
5.358268e-01
3.141076e-02
-4.817537e-01
-8.607420e-01
-1
-8.607420e-01
-4.817537e-01
3.141076e-02
5.358268e-01
8.910065e-01
9.980267e-01
8.270806e-01
4.257793e-01
-9.410831e-02
-5.877853e-01
-9.177546e-01
-9.921147e-01
-7.901550e-01
-3.681246e-01
1.564345e-01
6.374240e-01
9.408808e-01
9.822873e-01
7.501111e-01
3.090170e-01
-2.181432e-01
-6.845471e-01
-9.602937e-01
-9.685832e-01
-7.071068e-01
-2.486899e-01
2.789911e-01
Assuming the file is not exceedingly large, the simplest way would probably be read the entire file & index the output to your desired lines.
line = [6 11 111 127];
fileID = fopen('file.txt');
C = textscan(fileID,'%s','delimiter','\n');
fclose(fileID);
disp(C{1}(line))

Tensorflow: Cannot interpret feed_dict key as Tensor

I am trying to build a neural network model with one hidden layer (1024 nodes). The hidden layer is nothing but a relu unit. I am also processing the input data in batches of 128.
The inputs are images of size 28 * 28. In the following code I get the error in line
_, c = sess.run([optimizer, loss], feed_dict={x: batch_x, y: batch_y})
Error: TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder_64:0", shape=(128, 784), dtype=float32) is not an element of this graph.
Here is the code I have written
#Initialize
batch_size = 128
layer1_input = 28 * 28
hidden_layer1 = 1024
num_labels = 10
num_steps = 3001
#Create neural network model
def create_model(inp, w, b):
layer1 = tf.add(tf.matmul(inp, w['w1']), b['b1'])
layer1 = tf.nn.relu(layer1)
layer2 = tf.matmul(layer1, w['w2']) + b['b2']
return layer2
#Initialize variables
x = tf.placeholder(tf.float32, shape=(batch_size, layer1_input))
y = tf.placeholder(tf.float32, shape=(batch_size, num_labels))
w = {
'w1': tf.Variable(tf.random_normal([layer1_input, hidden_layer1])),
'w2': tf.Variable(tf.random_normal([hidden_layer1, num_labels]))
}
b = {
'b1': tf.Variable(tf.zeros([hidden_layer1])),
'b2': tf.Variable(tf.zeros([num_labels]))
}
init = tf.initialize_all_variables()
train_prediction = tf.nn.softmax(model)
tf_valid_dataset = tf.constant(valid_dataset)
tf_test_dataset = tf.constant(test_dataset)
model = create_model(x, w, b)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(model, y))
optimizer = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
#Process
with tf.Session(graph=graph1) as sess:
tf.initialize_all_variables().run()
total_batch = int(train_dataset.shape[0] / batch_size)
for epoch in range(num_steps):
loss = 0
for i in range(total_batch):
batch_x, batch_y = train_dataset[epoch * batch_size:(epoch+1) * batch_size, :], train_labels[epoch * batch_size:(epoch+1) * batch_size,:]
_, c = sess.run([optimizer, loss], feed_dict={x: batch_x, y: batch_y})
loss = loss + c
loss = loss / total_batch
if epoch % 500 == 0:
print ("Epoch :", epoch, ". cost = {:.9f}".format(avg_cost))
print("Minibatch accuracy: %.1f%%" % accuracy(predictions, batch_labels))
valid_prediction = tf.run(tf_valid_dataset, {x: tf_valid_dataset})
print("Validation accuracy: %.1f%%" % accuracy(valid_prediction.eval(), valid_labels))
test_prediction = tf.run(tf_test_dataset, {x: tf_test_dataset})
print("TEST accuracy: %.1f%%" % accuracy(test_prediction.eval(), test_labels))
This worked for me
from keras import backend as K
and after predicting my data i inserted this part of code
then i had again loaded the model.
K.clear_session()
i faced this problem in production server,
but in my pc it was running fine
...........
from keras import backend as K
#Before prediction
K.clear_session()
#After prediction
K.clear_session()
Variable x is not in the same graph as model, try to define all of these in the same graph scope. For example,
# define a graph
graph1 = tf.Graph()
with graph1.as_default():
# placeholder
x = tf.placeholder(...)
y = tf.placeholder(...)
# create model
model = create(x, w, b)
with tf.Session(graph=graph1) as sess:
# initialize all the variables
sess.run(init)
# then feed_dict
# ......
If you use django server, just runserver with --nothreading
for example:
python manage.py runserver --nothreading
I had the same issue with flask. adding --without-threads flag to flask run or threaded=False to app.run() fixed it
In my case, I was using loop while calling in CNN multiple times, I fixed my problem by doing the following:
# Declare this as global:
global graph
graph = tf.get_default_graph()
# Then just before you call in your model, use this
with graph.as_default():
# call you models here
Note: In my case too, the app ran fine for the first time and then gave the error above. Using the above fix solved the problem.
Hope that helps.
The error message TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("...", dtype=dtype) is not an element of this graph can also arise in case you run a session outside of the scope of its with statement. Consider:
with tf.Session() as sess:
sess.run(logits, feed_dict=feed_dict)
sess.run(logits, feed_dict=feed_dict)
If logits and feed_dict are defined properly, the first sess.run command will execute normally, but the second will raise the mentioned error.
You can also experience this while working on notebooks hosted on online learning platforms like Coursera. So, implementing following code could help get over with the issue.
Implement this at the topmost block of Notebook file:
from keras import backend as K
K.clear_session()
Similar to #javan-peymanfard and #hmadali-shafiee, I ran into this issue when loading the model in an API. I was using FastAPI with uvicorn. To fix the issue I just set the API function definitions to async similar to this:
#app.post('/endpoint_name')
async def endpoint_function():
# Do stuff here, including possibly (re)loading the model

Setting to get the pretty rational phrases in command window

Here I've a rational relation :
A = -(2*omega*(5*omega^4 - 9907*omega^2 + 550))/(omega^6 + 5025*omega^4 + 3344500*omega^2 + 11902500)
Is there any setting in Matlab that shows computed results in command window 'like (A)' pretty as below form (both for numeric and parametric results):
-(2*omega*(5*omega^4 - 9907*omega^2 + 550))
A = --------------------------------------------------------
(omega^6 + 5025*omega^4 + 3344500*omega^2 + 11902500)
You might want to check out pretty.
From the documentation:
pretty(X) prints symbolic output of X in a format that resembles typeset mathematics.
As an example:
/ 2 \
sqrt(3) | ---- + #2 | 1i
\ 9 #2 /
------------------------
2
I don't have the symbolic toolbox, so I can't illustrate with your example.