How to implement similar statements in matlab using a loop? - matlab

Look at the code snippet here in the mathworks documentation,
Digital Servo Control of a Hard-Disk Drive
Gf1 = tf(w1*[a1 b1*w1],[1 2*z1*w1 w1^2]); % first resonance
Gf2 = tf(w2*[a2 b2*w2],[1 2*z2*w2 w2^2]); % second resonance
Gf3 = tf(w3*[a3 b3*w3],[1 2*z3*w3 w3^2]); % third resonance
Gf4 = tf(w4*[a4 b4*w4],[1 2*z4*w4 w4^2]); % fourth resonance
my question is, how can I implement the above statements within a loop like,
% pseudo code
for i = 1:4
Gf%d = tf(w%d*[a%d b%d*w%d],[1 2*z%d*w%d w%d^2]); i
and then execute the result in matlab?

Here's one option:
w = [w1 w2 w3 w4];
%# same thing for a, b, d...
for i=1:4
Gf(i) = tf(w(i)*[a(i) b(i)*w(i)],[1 2*z(i)*w(i) w(i)^2]); % ith resonance
end

You could either use eval:
for i = 1:4
eval(sprintf('Gf%d = tf(w%d*[a%d b%d*w%d],[1 2*z%d*w%d w%d^2]);', i));
end
or you could turn your parameters into arrays. Arrays would be more efficient, if you have control over how you format your data.

The best way to do this is to use arrays.
for i = 1:n
trans(i) = % your stuff here %
end
Then just replace the different variables with the correct array indexes.

Related

How to do an animate plot in MATLAB from a sequence of matrices

I have code that uses Wolff's Algorithm to simulate the XY Model in MATLAB and I want to implement a pcolor/color map to demonstrate each spin according to their angles across the system. But I want it to be live and changing as the angles change.
Any idea how to do this?
This is an example of how I want it to look https://i.stack.imgur.com/aSp7s.png
If you save each snapshot of the lattice in a cell array A{t}, you can use the following function to view and save it as a video (if fileName is not empty, the function saves an mp4 video).
Another option is to adapt the function view_lattice to run your simulation (which, honestly, I wouldn't recommend, for performance issues). I will mark where you should edit for doing a "live" simulation
This is at least MATLAB R2019b (although it may be compatible with earlier versions, but no guarantee).
File view_lattice.m
function view_lattice(A,fileName)
% for a 'live' simulation, you will have to remove A from the input
% parameters and add the ones you need for the XY Wolff algorithm,
% which will be used to calculate each configuration A in the time loop below
% you will also need to remove the assert statements for 'live' simulation
%
% otherwise, you save snapshots from your simulation
% and use this function as is
%
% A -> A{k}[m,n] snapshot k containing the angles of spins in lattice site at row m and col n
% fileName -> if contains string, then records a video with the snapshots and name it with this string
assert(iscell(A) && all(cellfun(#(a)isnumeric(a) && ismatrix(a),A)),'A must be cell of numeric matrices');
assert(ischar(fileName),'fileName must be either an empty char or contain a file name');
recordVideo = ~isempty(fileName);
if recordVideo
vw = setup_video(fileName);
else
vw = [];
end
% setting some default axis properties to speed-up plotting
set(0,'DefaultAxesPlotBoxAspectRatio',[1 1 1],'DefaultAxesDataAspectRatioMode','manual','DefaultAxesDataAspectRatio',[1,1,1],'DefaultAxesNextPlot','replace');
fh = figure;
ax=axes;
for t = 1:numel(A) % for 'live' simulation, this loop should be the time loop
% here you calculate the new configuration A
% and call the function below with A instead of A{t}
vw = record_frame(vw,fh,ax,A{t},t,recordVideo);
end
% any video to close?
if recordVideo
vw.close();
end
end
function vw = record_frame(vw,fh,ax,A,t,recordVideo)
imagesc(ax,A);
title(ax,sprintf('snapshot %g',t)); % if you want, y
axis(ax,'square');
daspect(ax,[1,1,1]);
pause(0.01);
if recordVideo
vframe = getframe(fh);
vw.writeVideo(vframe);
end
end
function vw = setup_video(fileName)
vid_id = num2str(rand,'%.16g');
vid_id = vid_id(3:6);
vid_id = [fileName,'_',vid_id];
% Initialize video
vw = VideoWriter([vid_id,'.mp4'], 'MPEG-4'); %open video file
vw.Quality = 100;
vw.FrameRate = 16;
vw.open();
end
Test script: test.m
clearvars
close all
A = cell(1,30);
for t = 1:numel(A)
% creating a sequence of random snapshots only for illustration
A{t} = rand(20,20);
end
% viewing the animation and saving it as a video with name test
view_lattice(A,'test');
Output

insert value in a matrix in a for loop

I wrote this matlab code in order to concatenate the results of the integration of all the columns of a matrix extracted form a multi matrix array.
"datimf" is a matrix composed by 100 matrices, each of 224*640, vertically concatenated.
In the first loop i select every single matrix.
In the second loop i integrate every single column of the selected matrix
obtaining a row of 640 elements.
The third loop must concatenate vertically all the lines previously calculated.
Anyway i got always a problem with the third loop. Where is the error?
singleframe = zeros(224,640);
int_frame_all = zeros(1,640);
conc = zeros(100,640);
for i=0:224:(22400-224)
for j = 1:640
for k = 1:100
singleframe(:,:) = datimf([i+1:(i+223)+1],:);
int_frame_all(:,j) = trapz(singleframe(:,j));
conc(:,k) = vertcat(int_frame_all);
end
end
end
An alternate way to do this without using any explicit loops (edited in response to rayryeng's comment below. It's also worth noting that using cellfun may not be more efficient than explicitly looping.):
nmats = 100;
nrows = 224;
ncols = 640;
datimf = rand(nmats*nrows, ncols);
% convert to an nmats x 1 cell array containing each matrix
cellOfMats = mat2cell(datimf, ones(1, nmats)*nrows, ncols);
% Apply trapz to the contents of each cell
cellOfIntegrals = cellfun(#trapz, cellOfMats, 'UniformOutput', false);
% concatenate the results
conc = cat(1, cellOfIntegrals{:});
Taking inspiration from user2305193's answer, here's an even better "loop-free" solution, based on reshaping the matrix and applying trapz along the appropriate dimension:
datReshaped = reshape(datimf, nrows, nmats, ncols);
solution = squeeze(trapz(datReshaped, 1));
% verify solutions are equivalent:
all(solution(:) == conc(:)) % ans = true
I think I understand what you want. The third loop is unnecessary as both the inner and outer loops are 100 elements long. Also the way you have it you are assigning singleframe lots more times than necessary since it does not depend on the inner loops j or k. You were also trying to add int_frame_all to conc before int_frame_all was finished being populated.
On top of that the j loop isn't required either since trapz can operate on the entire matrix at once anyway.
I think this is closer to what you intended:
datimf = rand(224*100,640);
singleframe = zeros(224,640);
int_frame_all = zeros(1,640);
conc = zeros(100,640);
for i=1:100
idx = (i-1)*224+1;
singleframe(:,:) = datimf(idx:idx+223,:);
% for j = 1:640
% int_frame_all(:,j) = trapz(singleframe(:,j));
% end
% The loop is uncessary as trapz can operate on the entire matrix at once.
int_frame_all = trapz(singleframe,1);
%I think this is what you really want...
conc(i,:) = int_frame_all;
end
It looks like you're processing frames in a video.
The most efficent approach in my experience would be to reshape datimf to be 3-dimensional. This can easily be achieved with the reshape command.
something along the line of vid=reshape(datimf,224,640,[]); should get you far in this regard, where the 3rd dimension is time. vid(:,:,1) then would display the first frame of the video.

Undefined function 'minus' for input argument of type 'iddata'

This is a followup to a previous issue I was having.
I want to give an offset to a signal then add some delay in it and calculate RMSE for that but when taking difference I am having the following issue:
I would like to ask the following things:
How can I solve the above problem?
Will anybody please explain in simple words what iddata does - because I have studied different portals including MATLAB but remained unable to get a good concept.
How can I store data of type iddata in cell for subtraction in the last part of my code?
Code with Problem :
drv(1)=load('123.mat');
t = drv(1).x;
ref = drv(1).y;
angle = drv(1).z;
Fs = 1000;
t1 =t';
ref1= ref';
d_data = iddata(ref1, t1, 1/Fs);
%% Add offset:
x = 1;
afterOffset1= {};
for i = 100:10:130
T = getTrend(d_data);
% <detrend data if needed>
T.InputOffset = i;
T.OutputOffset = i;
afterOffset = retrend(d_data,T);
afterOffset1{x,1}= afterOffset;
x= x+1 ;
end
%% Add delay:
y=20;
afterDelay1= {};
for i = 1:1:4
% delaySamples = i; % Must be a non-negative value
% afterDelay = iddata([NaN(delaySamples,1); d_data.OutputData],...
% [d_data.InputData; NaN(delaySamples,1)], 1/Fs);
afterOffset1{i}.Tstart = y;
afterDelay1{i,1}= afterOffset1{i};
y= y+10;
end
%% Plot:
n = size(afterDelay1,1);
figure();
for i=1:1:n
subplot(2,2,i);
plot(d_data);
hold all
plot(afterDelay1{i});
end
sig_diff = angle(1)-afterDelay1;
square_error(i,:) = (sig_diff(i)).^2;
mse(i,:)= mean(square_error(i));
rmse(i,:) = sqrt(mse(i));
sig_diff = d_data_1 - afterDelay; % <<<<<<<<<<<<<<<<<<<<<< Problem is here
% square_error = (sig_diff).^2;
% mse= mean(square_error);
% rmse = sqrt(mse);
end
You most likely want the OutputData attribute from the iddata object which is the output or y signal of your problem:
sig_diff = angle(1)-afterDelay1.OutputData;
Also note that this will give you a column vector, but your code later on assumes it's a row vector. You may want to transpose this data after you perform the above calculation before proceeding:
sig_diff = angle(1)-afterDelay1.OutputData;
sig_diff = sig_diff.';
In general, iddata is a function that creates an object that represents input and output time or frequency domain data. Take note that when you create an iddata object, the input matrix can potentially have multiple sources and so each column dictates a source. The same can be said for the output where each column dictates an output. Therefore, it is very important that you transpose your data prior to using this function to ensure that each signal is in a separate column, or just use a single column to represent one input / output.
Inside the object has a variety of attributes, including the sampling time or sampling frequency, the valid domain and range that the function takes on and finally accessing the input and output data. OutputData is one of these fields. I'd recommend looking at the documentation that talks about all of the attributes that you can access with iddata. OutputData is clearly defined here: https://www.mathworks.com/help/ident/ref/iddata.html

Undefined function or variable 'resubPredict'. Why?

I have MATLAB R2015b and I am working on a Pattern Recognition project. I have loaded fisher iris data set.
I have written the code below for k-NN classification:
rng default;
fold_number = 5;
indices = crossvalind('Kfold',species, fold_number);
val = 1:2:5; % for these small k values there will not be an important difference
% regarding the cp ErrorRates. The difference is going to be
% observable for val = 1:2:100, for example!!! But the
% exercise asks only for k = 1,3,5.
err_arr = [];
for k=val
cp = classperf(species); % Reinitialize the cp-structure!
for i = 1:fold_number
test = (indices == i);
train = ~test;
class = knnclassify(meas(test,:),meas(train,:),species(train), k);
%class = knnclassify(meas(test,2),meas(train,2),species(train), k); % To experiment only with the 2nd feature
classperf(cp,class,test);
end
err_arr = [err_arr; cp.ErrorRate];
fprintf('The k-NN classification error rate for k = %d is: %f\n', k,cp.ErrorRate);
end
fprintf('\n The error array is: \n');
disp(err_arr);
fprintf('Program paused. Press enter to continue.\n');
pause
After that, I would like to plot the confusion matrix. So, I need this line of code:
[C,order] = confusionmat(species, predicted_species);
So, I have to find the predicted_species matrix. I have thought to write the below line of code about that:
predicted_species = resubPredict(class);
Here is the moment I am getting the on the title mentioned error and I do not know why, while resubPredict is a function supported by my MATLAB version.
Could anyone help me solve this problem?
Take a look at the top of the documentation for resubPredict, there you will notice the line
Class ClassificationKNN
Meaning that the function can only be used with inputs of that type. In your case you are passing doubles.
You have to switch to the new interface, fitcknn instead of knnclassify

Fitting a curve using matlab

I have a plot with two intersecting parabolas. Is there a way that I can detect the two correctly and fit two parabolas, one through each of them? My current code fits only a single parabola:
x=-100:1:100;
y=(x.^2)/(4);
x1=-50:1:150;
y1=(x.^2)/(4);
x=[x,x1];
y=[y,y1];
f = fittype('((x)*(x))/4*p',...
'dependent',{'y'},'independent',{'x'},...
'coefficients',{'p'})
fit1= fit(x',y',f)
plot(fit1,x,y)
Following the suggestions I was able to write a code that runs ransac for curves
function [f1] = Ransac(x,y)
voting=[0,0,0,0];
for i=1:10000
[y1,idx] = datasample(y,5);
x1=x(idx);
p = polyfit(x1,y1,2);
f1 = polyval(p,x);
error=(((f1-y).^2));
error(error>100)=0;
indx =find(ismember(voting(:,1:3),'rows'),1);
if (isempty(indx)==1)
voting=[voting;[p,sum(error)]];
else
voting(indx,4) = voting(indx,4)+sum(error);
end
end
[s,t]=max(voting(:,4));
p=voting(t,1:3);
f1 = polyval(p,x);
end