Simulink: How to accept Vector (1d Matrix) input and output a single value - simulink

I'm trying to create a window averager function block that takes multiple inputs as a vector (1d Matrix) from a temperature sensor, divides the sum by the length and returns the window average.
inputs : u= 25,26,23,22
output: 24 [sum(u)/length(u)]
How do I do this?
If I wanted a vector output, how would I do that?
if I do
function y = fcn( u)
y = u/length(u);
I don't get what I want.

Related

Logistic regression in matlab using mnrfit

I'm trying to use the mnrfit function but I get the error
If Y is a column vector, it must contain positive integer category numbers. .
My data is in a double and my Y values are floats, e.g. 0.6667. Is there a way that I can adjust my data to be able to use the mnrfit function?
Thanks in advance!
An unexperienced beginner
Y should be a "nominal outcome", i.e. non-continuous, to use mnrfit. We don't need to turn Y into integers, just categoricals. A categorical array is discrete as far as MATLAB is concerned, regardless whether the categories are represented by double values.
X = rand(5,3); % Predictors (should be double or single)
Y = rand(5,1); % Response (doubles, will cause error)
B = mnrfit( X, Y )
% ERROR: If Y is a column vector, it must contain positive integer category numbers.
B = mnrfit( X, categorical(Y) )
% No error, regression matrix B is output successfully.
Be careful, if you're expecting a continuous response variable (hence why Y is a vector of doubles) then mnrfit may not be suitable in the first place!
Note the valid data types are specified in the docs
Y can be one of the following:
An n-by-k matrix, where Y(i,j) is the number of outcomes of the multinomial category j for the predictor combinations given by X(i,:). In this case, the number of observations are made at each predictor combination.
An n-by-1 column vector of scalar integers from 1 to k indicating the value of the response for each observation. In this case, all sample sizes are 1.
An n-by-1 categorical array indicating the nominal or ordinal value of the response for each observation. In this case, all sample sizes are 1.

Square wave function for Matlab

I'm new to programming in Matlab. I'm trying to figure out how to calculate the following function:
I know my code is off, I just wanted to start with some form of the function. I have attempted to write out the sum of the function in the program below.
function [g] = square_wave(n)
g = symsum(((sin((2k-1)*t))/(2k-1)), 1,n);
end
Any help would be much appreciated.
Update:
My code as of now:
function [yout] = square_wave(n)
syms n;
f = n^4;
df = diff(f);
syms t k;
f = 1; %//Define frequency here
funcSum = (sin(2*pi*(2*k - 1)*f*t) / (2*k - 1));
funcOut = symsum(func, v, start, finish);
xsquare = (4/pi) * symsum(funcSum, k, 1, Inf);
tVector = 0 : 0.01 : 4*pi; %// Choose a step size of 0.01
yout = subs(xsquare, t, tVector);
end
Note: This answer was partly inspired by a previous post I wrote here: How to have square wave in Matlab symbolic equation - However, it isn't quite the same, which is why I'm providing an answer here.
Alright, so it looks like you got the first bit of the question right. However, when you're multiplying things together, you need to use the * operator... and so 2k - 1 should be 2*k - 1. Ignoring this, you are symsuming correctly given that square wave equation. The input into this function is only one parameter only - n. What you see in the above equation is a Fourier Series representation of a square wave. A bastardized version of this theory is that you can represent a periodic function as an infinite summation of sinusoidal functions with each function weighted by a certain amount. What you see in the equation is in fact the Fourier Series of a square wave.
n controls the total number of sinusoids to add into the equation. The more sinusoids you have, the more the function is going to look like a square wave. In the question, they want you to play around with the value of n. If n becomes very large, it should start approaching what looks like to be a square wave.
The symsum will represent this Fourier Series as a function with respect to t. What you need to do now is you need to substitute values of t into this expression to get the output amplitude for each value t. They define that for you already where it's a vector from 0 to 4*pi with 1001 points in between.
Define this vector, then you'll need to use subs to substitute the time values into the symsum expression and when you're done, cast them back to double so that you actually get a numeric vector.
As such, your function should simply be this:
function [g] = square_wave(n)
syms t k; %// Define t and k
f = sin((2*k-1)*t)/(2*k-1); %// Define function
F = symsum(f, k, 1, n); %// Define Fourier Series
tVector = linspace(0, 4*pi, 1001); %// Define time points
g = double(subs(F, t, tVector)); %// Get numeric output
end
The first line defines t and k to be symbolic because t and k are symbolic in the expression. Next, I'll define f to be the term inside the summation with respect to t and k. The line after that defines the actual sum itself. We use f and sum with respect to k as that is what the summation calls for and we sum from 1 up to n. Last but not least, we define a time vector from 0 to 4*pi with 1001 points in between and we use subs to substitute the value of t in the Fourier Series with all values in this vector. The result should be a 1001 vector which I then cast to double to get a numerical result and we get your desired output.
To show you that this works, we can try this with n = 20. Do this in the command prompt now:
>> g = square_wave(20);
>> t = linspace(0, 4*pi, 1001);
>> plot(t, g);
We get:
Therefore, if you make n go higher... so 200 as they suggest, you'll see that the wave will eventually look like what you expect from a square wave.
If you don't have the Symbolic Math Toolbox, which symsum, syms and subs relies on, we can do it completely numerically. What you'll have to do is define a meshgrid of points for pairs of t and n, substitute each pair into the sequence equation for the Fourier Series and sum up all of the results.
As such, you'd do something like this:
function [g] = square_wave(n)
tVector = linspace(0, 4*pi, 1001); %// Define time points
[t,k] = meshgrid(tVector, 1:n); %// Define meshgrid
f = sin((2*k-1).*t)./(2*k-1); %// Define Fourier Series
g = sum(f, 1); %// Sum up for each time point
end
The first line of code defines our time points from 0 to 4*pi. The next line of code defines a meshgrid of points. How this works is that for t, each column defines a unique time point, so the first column is 200 zeroes, up to the last column which is a column of 200 4*pi values. Similarly for k, each row denotes a unique n value so the first row is 1001 1s, followed by 1001 2s, up to 1001 1s. The implications with this is now each column of t and k denotes the right (t,n) pairs to compute the output of the Fourier series for each time that is unique to that column.
As such, you'd simply use the sequence equation and do element-wise multiplication and division, then sum along each individual column to finally get the square wave output. With the above code, you will get the same result as above, and it'll be much faster than symsum because we're doing it numerically now and not doing it symbolically which has a lot more computational overhead.
Here's what we get when n = 200:
This code with n=200 ran in milliseconds whereas the symsum equivalent took almost 2 minutes on my machine - Mac OS X 10.10.3 Yosemite, 16 GB RAM, Intel Core i7 2.3 GHz.

Plotting Convolution in Matlab

I am trying to use matlab to plot the convolution of two functions, on a set interval of time, and cannot get the plot function to work.
My code so far is this:
>> t = -10:.1:10
>> f = heaviside(t)-heaviside(t-3)
>> g = heaviside(t)-heaviside(t-1)
>> y = conv(f,g)
which produces 3 variables of "value" 1x201 double, (t, f, g) and the convolution which is of value 1x401 double, which I believe means it is double the amount of points of the previous variables
When I go to plot this using the plot command I try to plot the convolution with respect to t, using this command:
>> plot(t,y)
which throws and error saying "vectors must be the same length". How do I make it so that I can plot y with respect to t?
The range of t for the convolution should be from two times the minimum value of the original range to two time the maximum value of the original range, at the same interval. Therefore the number of values of t for the convolution is 2*n - 1 where n is the original number of values of t. So in summary I think you can say t = -20 : 0.1 : 20 and then you should have the correct range and the correct number of values of t. EDIT: corrected step size; should be the same (namely 0.1) as the original range.
More generally, if you are convolving two series which have different ranges, the minimum value of the range of the result is the sum of the minimum values of the original ranges, and the maximum is the sum of the original ranges' maximum values.

Plotting a Matrix in matlab with float elements

I have results of an experiment which is parameter optimization of support vector regression. I have the first three columns the parameters and the last column the MSE so I have about 24,646 X 4 matrix. I would like to get the parameters corresponding to the smallest MSE. How can I plot this on Matlab? the elements of the matrix are float numbers. Thank you for your help.
Use second output of min to obtain the index of the minimum value in the fourth columns; and then use that to get the parameters:
[~, ind] = min(matrix(:,4));
params = matrix(ind,1:3);

How to do windowing, FFT and display result

I'm trying to input a .wav file by
filename = 'C:\Users\kiit\Desktop\New folder\file.wav';
[y, Fs, nbits] = wavread(filename)
after that I'm calculate the length by-
L=length(y)
I've performed hamming window by-
w=window(#hamming,L);
when I perform fft by
F=fft(y,w)
It's showing warning as
Warning: FFT length must be a non-negative integer scalar.
F =
Empty matrix: 0-by-1
Any help??
Your fft command is wrong. The second argument is the FFT length, not the window.
Y = fft(X,n) returns the n-point DFT. fft(X) is equivalent to fft(X, n) where n
is the size of X in the first nonsingleton dimension. If the length of X is less
than n, X is padded with trailing zeros to length n. If the length of X is
greater than n, the sequence X is truncated. When X is a matrix, the length of
the columns are adjusted in the same manner.
To window, you apply (elementwise multiply) in the time domain (i.e. y.*w).
And to understand the output of fft:
Why does FFT produce complex numbers instead of real numbers?
Converting Real and Imaginary FFT output to Frequency and Amplitude