Subplot matlab

Digital communication- operations on some cosines (samples filters reconstructions and such)

2023.05.14 11:58 daniel655422 Digital communication- operations on some cosines (samples filters reconstructions and such)

Hey folks, what's going on?
so...I received some matlab assignments from submit to my dear professor:
I can use the following data %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close all; clear all; clc; %% Tc=1/400; % sampling period of "continuous signal" [sec] Ts=1/50; % sampling period [sec] f0=10; % frequency of the signal [Hz] tc=0:Tc:0.4; % time axis of continuous signal ts=0:Ts:0.4; % time axis of sampeled signal %% Xc=cos(2*pi*f0*tc); % continuous signal Xs=cos(2*pi*f0*ts); % sampeled signal %% fh = figure(1); fh.WindowState = 'maximized'; % full screen plot plot(tc,Xc,'b','linewidth',3) hold on stem(ts,Xs,'.r','linewidth',3,'markersize',20) xlabel('Time [Sec]') legend('Continuous signal','Sampeled signal') set(gcf,'color','w'); % white background 
For the purpose of illustrating the continuous signal, an interval between samples Tc of 1/400 seconds was set for it.
This is the interval for it
We will present and restore the signal at the end. Ts is the interval between the samples and is equivalent to the sampling frequency, this variable will change accordingly
to the task
f0 is the frequency of the signal and will change depending on the task.
Given the following signals: 1. πΆπ‘œπ‘ (2πœ‹10𝑑) 2. πΆπ‘œπ‘ (2πœ‹20𝑑) 3. πΆπ‘œπ‘ (2πœ‹30𝑑) 4. πΆπ‘œπ‘ (2πœ‹40𝑑) 5. πΆπ‘œπ‘ (2πœ‹10𝑑)+2πΆπ‘œπ‘ (2πœ‹30𝑑) when the sampling frequency is fs=50Hz
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Assignment 1:
For each of the signals build the following output:
Subfigure 1
Subfigure 2
Where sub-figure 1 contains the continuous signal and the sampled signal and sub-figure 2 contains the productive transform of the sampled signal. explanation
the results you got.
Assignment 2:
In order to avoid the phenomenon of spectrum aliasing, before the sampling operation, the signal must be filtered with an LPF filter
suitable
For this purpose a 2nd order butterwort type filter was chosen.
a. Use the filterDesigner tool and select the appropriate filter and attach its transfer function.
b. To validate the filter, construct a white noise corresponding to the sampling frequency of the signal and pass it through the filter and show the
The spectrum of the noise before and after filtering.
c. Repeat section b for each of the defined signals.
Assignment 3:
For the purpose of the reconstruction operation, we will define a number axis corresponding to the definition of the continuous signal (according to Tc). At each point in time we have a sample,
The sample will appear and all other places will have zeros. For each of the signals construct the following output:
Subfigure 1
Subfigure 2
Where sub-figure 1 contains the signal in the timeline and sub-figure 2 contains the derivative transform of the signal. Explain the results
you got
Assignment 4:
As we saw in assignment 3, since we have partial information about the reconstructed signal we got a phenomenon of "spectral duplication". as my hand
To overcome the phenomenon and get a desired reproduced signal it is necessary to "smooth the signal". The swipe operation is a filter type operation
LPF when the filter must be chosen correctly.
a. Explain the considerations for choosing the filter.
b. Use a 2nd order butterwort filter and smooth the signal.
c. Use an ideal filter (Sinc train as we saw in the lecture).
For sections b,c, describe and show the transfer function of the selected filter. Show the productive transformation of the signals
before and after the filtering operation.
d. Show in the timeline the original signal versus the reconstructed signal for the two filters from sections b,c. If accepted
Delay between signals Explain the meaning and/or lack of delay obtained
Assignment 5:
Data from two uniform quantifiers with 8 and 16 quantification levels respectively. The value of their extreme levels is Β±1.
The following signals enter the quantizer:
a. y=x , -1.5 b. 𝑦=πΆπ‘œπ‘ (2πœ‹20𝑑)
c. 𝑦=πΆπ‘œπ‘ (2πœ‹10𝑑)+ 0.5πΆπ‘œπ‘ (2πœ‹25𝑑)
d. y~U[-1,1]
e. y~U[-2,0]
f. y~U[-2,2]
g. y~N(0,0.2)
h. y~N(0,0.4)
i. y~N(-0.5,0.5)
Plot the original signal, the quantized signal and the quantized noise for the first three signals and calculate the resulting SQNR
for all signals.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%I think EX1 is good this is what I tried%
clear;clc;close all;%%Tc=1/400; % constant sampling period of "continuous signals" [sec]Ts=1/50; % new given sampling period [sec]fs=1/Ts; % new given sampling frequency [Hz]f0=10; % frequency of the first signal [Hz]tc=0:Tc:0.4; % time axis of continuous signalts=0:Ts:0.4; % time axis of sampeled signalf1234=f0*[1 2 3 4]; % frequencies for the first 4 cos wavesXccounter=zeros(4,length(tc)); % matrix of zeros for continuous signalsXscounter=zeros(length(f1234)+1,length(ts)); % matrix of zeros for sampeled signals%%for i=1:4 % for loop 1 to create array of the first 4 signalsXccounter(i,:)=cos(2*pi*f1234(i)*tc); % continuous signalsXscounter(i,:)=cos(2*pi*f1234(i)*ts); % sampeled signalsend % end of loop 1%%Xccounter(5,:)=Xccounter(1,:)+2*Xccounter(3,:); % assign the fifth continuous signal value to arrayXscounter(5,:)=Xscounter(1,:)+2*Xscounter(3,:); % assign the fifth sampeled signal element to arrayfor ii=5:-1:1 %for loop 2 to create the subplots and calculate the fourier transformstat=figure(ii);% tat.WindowState='maximized'; % full screen plotssubplot(2,1,1)p1=plot(tc,Xccounter(ii,:),"r",'linewidth',1,"markersize",18);hold ons1=stem(ts,Xscounter(ii,:),"*b","linewidth",1,"markersize",7);xlabel('Time [Sec]')legend('Continuous signal','Sampeled signal',"Location","bestoutside")legend('boxoff')grid ontitle(['Signal',num2str(ii)]) % add title to subplothold offsubplot(2,1,2)Xsf=abs(fftshift(fft(Xscounter(ii,:))));f=linspace(-fs/2,fs/2,length(Xsf)); % calculate frequency range% Find the main frequency points of the two deltas for each cosine[~,idx_max]=max((Xsf)); % Find the index of maximum value and corresponding frequencyf_max =abs(f(idx_max));hold onp2=plot(f,(Xsf),"r",'linewidth',1,"markersize",18);s2=stem(f,(Xsf),"*b",'linewidth',1,"markersize",7);xlabel('Frequency [Hz]')title(['Fourier Transform of Signal',num2str(ii)])% add title to subplotsyline(Xsf(idx_max),"g",['f_{max} =',num2str(f_max),'Hz'],'LabelHorizontalAlignment','center','LabelVerticalAlignment','bottom','LineStyle',':','LineWidth',3);xline([-f_max,f_max],"g",'f_{ 0}Β±','LabelOrientation','horizontal','LineStyle',':','LineWidth',3);l2=legend([p2 s2],"Sampled Signal fft","Signal fft","Location","bestoutside");legend('boxoff')grid onpause(0.25)end
%I think EX2 is bad because i stil getting Alasing and dont see the fft in the original freq of the signal is what I tried%
I guess we all know the legendary Shannon and the mighty Nyquist with their theory of good lossless sampling,I don't know why, but when I asked the professor in class, he told me to build the filter like this, so I would appreciate an explanation as to why we don't set fs=80, which anyway is 2 times greater than the maximum frequency of the cos, but FS=400?
https://ibb.co/nRbtxC2
first try of EX2:
close all;clear;clc;%% EX2a %%load("LPF.mat","Fs400fs25"); % Load the filter object from the .mat fileLPF=Fs400fs25; % assigns the value "Fs400fs25" to the variable LPF[numerator,denominator]=tf(LPF); % obtain the transfer function% sys=tf(numerator,denominator);%end of EX2a%Tc=1/400; % constant sampling period of "continuous signals" [sec]Ts=1/50; % new given sampling period [sec]fs=50; % new given sampling frequency [Hz]f0=10; % frequency of the first signal [Hz]tc=0:Tc:0.4; % time axis of continuous signalts=0:Ts:0.4; % time axis of sampeled signalf=linspace(-fs/2,fs/2,length(tc)); % calculate frequency range%% EX2b %%noice=randn(size(tc));filltnoice=filter(LPF,noice);noicespectrum=abs(fftshift(fft(noice)))/length(tc);filltnoicespectrum=abs(fftshift(fft(filltnoice)))/length(tc);figure(6)subplot(2,1,1)plot(tc,noice,"r",tc,filltnoice,'b')legend('unfilltered noice red','filltered noice blue')title("white noice")subplot(2,1,2)plot(f,noicespectrum,"r",f,filltnoicespectrum,"b")hold onstem(f,noicespectrum,"r")stem(f,filltnoicespectrum,"b")legend('unfilltered fft red','filltered fft blue')title("noice spectrum")%end of EX2b%%% EX2c %%f1234=f0*[1 2 3 4]; % frequencies for the first 4 cos wavesXccounter=zeros(length(f1234),length(tc)); % matrix of zeros for continuous signalsXscounter=zeros(length(f1234),length(ts)); % matrix of zeros for sampled signalsfor i=1:4 % for loop 1 to create array of the first 4 signalsXccounter(i,:)=Xccounter(i,:)+cos(2*pi*f1234(i)*tc); % continuous signalsXscounter(i,:)=Xscounter(i,:)+cos(2*pi*f1234(i)*ts); % sampeled signalsend % end of loop 1Xccounter(5,:)=Xccounter(1,:)+2*Xccounter(3,:); % assign the fifth continuous signal value to arrayXscounter(5,:)=Xscounter(1,:)+2*Xscounter(3,:); % assign the fifth sampeled signal element to arrayfor ii=5:-1:1 %for loop 2 to create the subplotstat=figure(ii);% tat.WindowState='maximized'; % full screen plotssubplot(4,1,1)plot(tc,Xccounter(ii,:),'r','linewidth',3)hold onstem(ts,Xscounter(ii,:),'.g','linewidth',3,'markersize',20)xlabel('Time [Sec]')ylabel('Amplitude [TD]')legend('Continuous signal red','Sampeled signal green')title(['Signal',num2str(ii)]) % add title to subplothold offsubplot(4,1,3)Xsf=abs(fftshift(fft(Xccounter(ii,:))))/length(tc);plot(f,Xsf,'r')legend('Fourier Transform of Sampled Signal r')title(['Signal',num2str(ii)]) % add title to subplotxlabel('Frequency [Hz]')ylabel('Amplitude [FD]')subplot(4,1,4)xsfilt=abs(fftshift(fft(filter(LPF,Xccounter(ii,:)))));plot(f,xsfilt/length(tc),'b')xlabel('Frequency [Hz]')ylabel('Amplitude [FD]')legend("Fourier Transform of Sampled filtered Signal b")title(['Signal',num2str(ii)]) % add title to subplotxlabel('Frequency [Hz]')ylabel('Amplitude [FD]')subplot(4,1,2)plot(tc,filter(LPF,Xccounter(ii,:)),'b','linewidth',3)hold onstem(ts,Xscounter(ii,:),'.g','linewidth',3,'markersize',20)xlabel('Time [Sec]')ylabel('Amplitude [TD]')legend('Continuous filltered signal blue','Sampeled signal green')title(['Signal',num2str(ii)]) % add title to subplothold off;end%end of EX2c%
second try of EX2:
clear;clc;close all;%%Tc=1/400; % constant sampling period of "continuous signals" [sec]Ts=1/50; % new given sampling period [sec]fs=1/Ts; % new given sampling frequency [Hz]f0=10; % frequency of the first signal [Hz]tc=0:Tc:0.4; % time axis of continuous signalts=0:Ts:0.4; % time axis of sampeled signalf=linspace(-fs/2,fs/2,length(tc)); % calculate frequency rangef1234=f0*[1 2 3 4]; % frequencies for the first 4 cos wavesXccounter=zeros(4,length(tc)); % matrix of zeros for continuous signalsXscounter=zeros(length(f1234)+1,length(ts)); % matrix of zeros for sampeled signals%%%load("LPF.mat","Fs400fs25"); % LΧͺoad the filter object from the .mat fileLPF_1=Fs400fs25; % assigns the value "Fs400fs25" from the structure "matcontents" to the variable[numerator,denominator]=tf(Fs400fs25); % obtain the transfer functiontransferfunction=tf(numerator,denominator);%%%%%for i=1:4 % for loop 1 to create array of the first 4 signalsXccounter(i,:)=cos(2.*pi.*f1234(i).*tc); % continuous signalsXscounter(i,:)=cos(2.*pi.*f1234(i).*ts); % sampeled signalsend % end of loop 1%%Xccounter(5,:)=Xccounter(1,:)+2.*Xccounter(3,:); % assign the fifth continuous signal value to arrayXscounter(5,:)=Xscounter(1,:)+2.*Xscounter(3,:); % assign the fifth sampeled signal element to arrayfor ii=1:5 %for loop 2 to create the subplots and calculate the fourier transformstat=figure(ii);tat.WindowState='maximized'; % full screen plotssubplot(2,1,2)hold onXsf=abs(fftshift(fft(filter(LPF_1,Xccounter(ii,:),2))))/length(tc);p2=plot(f,(Xsf),"r",'linewidth',1,"markersize",18);s2=stem(f,(Xsf),"*b",'linewidth',1,"markersize",7);% Find the main frequency points of the two deltas for each cosine[~,idx_max]=max((Xsf)); % Find the index of maximum value and corresponding frequencyf_max =abs(f(idx_max));xlabel('Frequency [Hz]')title(['Fourier Transform of Signal',num2str(ii)])% add title to subplotsyline(Xsf(idx_max),"g",['f_{max} =',num2str(f_max),'Hz'],'LabelHorizontalAlignment','center','LabelVerticalAlignment','bottom','LineStyle',':','LineWidth',3);xline([-f_max,f_max],"g",'f_{ 0}Β±','LabelOrientation','horizontal','LineStyle',':','LineWidth',3);l2=legend([p2 s2],"Sampled Signal fft","Signal fft","Location","bestoutside");legend('boxoff')grid onhold offsubplot(2,1,1)p1=plot(tc,filter(LPF_1,Xccounter(ii,:)),"r",'linewidth',1,"markersize",18);hold ons1=stem(ts,Xscounter(ii,:),"*b","linewidth",1,"markersize",7);xlabel('Time [Sec]')legend('Continuous signal','Sampeled signal',"Location","bestoutside")legend('boxoff')grid ontitle(['Signal',num2str(ii)]) % add title to subplothold offpause(0.2)end
ex 3:
clc;clear;close all;%% Define constants and parametersTc=1/400; % constant sampling period of "continuous signals" [sec]Ts=1/50; % new given sampling period [sec]fs=1/Ts; % new given sampling frequency [Hz]f0=10; % frequency of the first signal [Hz]tc=0:Tc:0.4; % time axis of continuous signalts=0:Ts:0.4; % time axis of sampled signalf1234=f0*[1 2 3 4]; % frequencies for the first 4 cos waves%% Matrix of zeros for continuous and sampled signalsXccounter=zeros(length(f1234)+1,length(tc)); % matrix of zeros for continuous signalsXscounter=zeros(length(f1234)+1,length(ts)); % matrix of zeros for sampled signals%% Create the first 4 signalsfor i = 1:4Xccounter(i,:)=Xccounter(i,:)+cos(2*pi*f1234(i)*tc); % continuous signalsXscounter(i,:)=Xscounter(i,:)+cos(2*pi*f1234(i)*ts); % sampled signalsend%% Assign the fifth signal value to the sum of the first and third signalsXccounter(5,:)=Xccounter(1,:)+2*Xccounter(3,:); % assign the fifth continuous signal value to arrayXscounter(5,:)=Xscounter(1,:)+2*Xscounter(3,:); % assign the fifth sampled signal element to array%% create the subplotsfor ii=1:5figure(ii); % create figure% Plot the continuous and sampled signals in time domainsubplot(2,1,1)not_filtered=Xccounter(ii,:);plot(tc,not_filtered,'b','linewidth', 2);hold onstem(ts, Xscounter(ii,:), 'r', 'linewidth',1,'markersize',2);xlabel('Time [sec]');ylabel('Amplitude [V]');legend('Continuous signal', 'Sampled signal');title(['Signal',num2str(ii)]);hold off% Compute Fourier transform of the signal with zero-paddingN=length(tc);Xspadded=[Xscounter(ii,:),zeros(1,N*7)]; % zero-pad the signal% Plot the Fourier transform of the signalsubplot(2,1,2)fourier_on_unfiltered_cosines=abs(fftshift(fft(Xccounter(ii,:),N*8)));fourier_on_filtered_cosines=abs(fftshift(fft(Xspadded,N*8)));f=linspace(-fs/2,fs/2,length(fourier_on_unfiltered_cosines));plot(f,fourier_on_filtered_cosines,'b','linewidth',2);xlabel('Frequency [Hz]');ylabel('Amplitude [V]');legend('Fourier transform of sampled signal');title(['Signal',num2str(ii)]);end% End of ExerciseI've been sitting on this for several nights in a row and I'm living on coffee, stimulants, and energy drinks, please help me fall asleep (only if I finish this assignment will I go to sleep)
My questions are as follows:
  1. What do you think about the code, suggestions for improvement or preservation?
  2. Why am I trying to display the signals from assignment 1 in relation to the filtered signal in assignment 2 from the moment I used the filter (no matter which line and which display command) so everything is similar to the filtered one?
  3. I'll be honest with you, it seems to me that task 3 required zero padding or something, I couldn't really understand even though I tried with all my might, so I asked for help from GPT, but I don't think that's what they asked for, so could you please tell me what task 3 requires me to do?
  4. In the hope that we will reach a solution of 2 and I can go rest for a few hours. Do you have any suggestions, hints, instructions and instructions that will help me understand the rest of the questions (read about a certain topic and learn any commands and more)
That's it. I wish us abundance, blessings, health, joy, wealth and happiness. Thanks to those who can lend a hand hereβ™₯.
submitted by daniel655422 to matlab [link] [comments]


2023.04.30 22:28 ahsanansari100 discreet time coding help

discreet time coding help
Hi guys, im trying to code in matlab to create a discreet time code. I am trying to make it look like this (see picture) but it will have antiwindup and saturation. For some reason my output is oscillatory to my step input. I am a beginner in in discreet coding and I have coded in discreet so far please help:
Ts=0.23;
time=0:Ts:5;
Gp= tf([1.7 0],[1 5.06 0.71]);
Gpd= c2d(Gp,Ts,'tustin');
bode(Gp,Gpd);
b0=0.1229;
b1=0;
b2=-0.1229;
a0= 1;
a1=-1.245;
a2=0.2686;
Sat = 20;

% controller gains
Kp = 13;
Ki = 1.5;
Kd = 1;
AW = 0

% initialisation
u_c(1) = 0;
u_c(2) = 0;
y(1) = 0;
y(2) = 0;
ei(1) = 0;
ei(2) = 0;

for t=3:1:length(time) % loop to simulate the time
r(t) = 1; % generating the step input
e(t) = r(t)-y(t-1);
up(t) = Kp*e(t); % P term of PID
ei(t) = ei(t-1) + Ts*e(t); % error integration
ui(t) = Ki*ei(t); % I term of PID
ed(t) = 1/Ts*(e(t)-e(t-1));
ud(t) = Kd*ed(t);
if ui(t)>AW % if then rules to mimic saturation
ui(t)=AW;
elseif ui(t)<-AW
ui(t)=-AW;
else
ui(t)=AW;
end
u_c(t) = up(t) + ui(t); % control signal calculation
if u_c(t)>Sat % if then rules to mimic saturation
u_ac(t)=Sat;
elseif u_c(t)<-Sat
u_ac(t)=-Sat;
else
u_ac(t)=u_c(t);
end
% discrete time system implementation
y(t) = 1/a0*(-a1*y(t-1) - a2*y(t-2) + b0*u_ac(t) + b1*u_ac(t-1) + b2*u_ac(t-2));
ud(t)= -Kd*y(t)
end

% plot discrete-time setpoint and output
figure,
subplot(211)
plot(time,r,'r:',time,y,'b','linewidth',1.5)
ylabel('Output')
legend('r','y')
% plot the control signal

subplot(212)
plot(time,u_c,'r:',time,u_ac,'b','linewidth',1.5)
xlabel('Time(s)'), ylabel('Control signal'),legend('u_c','u_ac')

https://preview.redd.it/kopwp1vkz2xa1.jpg?width=533&format=pjpg&auto=webp&s=0e903017baedf8bd15705378834f6b8f6dda749e
https://preview.redd.it/c2fnkufjz2xa1.jpg?width=255&format=pjpg&auto=webp&s=0ad81a7bf857ef51b18299d67050600ca1e48ede
submitted by ahsanansari100 to matlab [link] [comments]


2023.04.12 19:16 WrongEinstein Thanks for helping me with subplot titles and axis titles. Reinstalled Matlab and your suggestions work now.

I apologize for being short with all of those folks that offered help. Basically, I noticed a few things weren't working that were in the wiki, so uninstalled and reinstalled. Now it generally works as the wiki says. But I think something on my end is corrupting it. As normal commands that worked are showing up as errors now. But different methods to perform the same functions work. Like linspace isn't working, but worked a couple days ago.
Anyway, my apologies to all the nice folks that offered help and the rest of the community. Thanks for all the help and have a great day!
submitted by WrongEinstein to matlab [link] [comments]


2023.03.23 21:36 Printedinusa Help with ode45 for a system of ODEs?

I'm very new to MATLAB and struggling a bit with a system of ODEs. While I've gotten my code to work just fine for only two ODEs, something seems to be going wrong for three or more. I'm getting an error that reads "@(T,Y)MYODE(T,Y,PARAMS) must return a column vector." If anyone could point out any obvious errors I'd be super appreciative.
code:
clc; clear; mu = -0.0001; alpha = 0.8; beta = 0.5; a = 0.1; b = 0.2; k = 0.5; m = 0.25; Dv = 0.7; Dh = 0.7; Qv = 1.0; Qh = 1.0; params = [mu; alpha; beta; a; b; k; m; Dv; Dh; Qv; Qh]; y0 = [0.3; 0.3; 0.1; 0.1; 1]; tspan = [0 50]; [t, y] = ode45(@(t,y)myODE(t,y,params), tspan, y0); subplot(2,1,1) plot(t,y) title('PredatoPrey Populations Over Time') xlabel('t') ylabel('Population') legend('Prey','Predators','Location','North') function dy = myODE(t,y,params) mu = params(1); alpha = params(2); beta = params(3); a = params(4); b = params(5); k = params(6); m = params(7); Dv = params(8); Dh = params(9); Qv = params(10); Qh = params(11); V1 = y(1); V2 = y(2); H1 = y(3); H2 = y(4); Vb = (V1 + V2) / 2; Hb = (H1 + H2) / 2; r = y(5); dy = zeros(5,4,3,2,1); dy(1) = r * V1 * (1 - (V1 / k)) * ((V1 - a) / k) - ((alpha * V1 * H1)/(V1 + b)) + Dv * (Qv * Vb - V1); dy(2) = r * V2 * (1 - (V2 / k)) * ((V2 - a) / k) - ((alpha * V2 * H2)/(V2 + b)) + Dv * (Qv * Vb - V2); dy(3) = beta * ((alpha * V1 * H1) / (V1 + b)) - (m * H1) + Dh * (Qh * Hb - H1); dy(4) = beta * ((alpha * V2 * H2) / (V2 + b)) - (m * H2) + Dh * (Qh * Hb - H2); dy(5) = mu; end 
errors:
Error using odearguments (line 93) @(T,Y)MYODE(T,Y,PARAMS) must return a column vector. Error in ode45 (line 106) odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin); Error in predatorprey (line 24) [t, y] = ode45(@(t,y)myODE(t,y,params), tspan, y0); 
submitted by Printedinusa to matlab [link] [comments]


2023.01.25 15:10 iBo0m PDEs with multiple phases - controlling constant boundary values throughout the simulation (ode15s).

I have a following favour: I am trying to solve a system of PDEs for a 1D flow (Z-axis) in time t having several phases distinct by different boundary conditions of mixed type (their duration is fixed by defining a time for each phase). I am using FVM with TVD.
.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. Problem description: my approach -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
Initially, I define initial conditions for t = 0, which I put in the resulting vector of unknown parameters. Next, I implement boundary conditions for the first phase for Z = 0 (Z = 0.5 for FVM) and Z = N (Z = N+0.5), respectively, and execute the ODE solver (ode15s as the set of PDEs is stiff).
I have noticed that during the time integration, the ode15s overwrites the boundary values for Z = 0.5, which I need to remain constant. Specifically, ode15s returns a non-zero values for the time derivatives at Z = 0.5, thus "changing" the boundary values for each time layer.
Arguably, this is not correct as the ode15s returns a non-zero values for the time derivatives on the Z = 0.5 boundary where they should be constant.
My solution: To "fix" this error, I have not found a better way than to zero (by "force") the time derivatives for Z = 0.5, after the ode15s has been computed, to achieve constant values at this boundary throughout the simulation.
Principally, the algorithm should work by defining the time derivatives only once at the beginning and then changing only the boundary conditions, in my opinion.
.-.-.-.-.-.-.-.-.-.-.-.- Numerical scheme and implementation of ICs and BCs .-.-.-.-.-.-.-.-.-.-.-.-.-
.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- MATLAB example: my implementation .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
I made a simple code document my problem and my implementation (the original code is "long"):
Questions
  1. What computation (implementation), different to mine, of the boundary conditions for the first time layer and for all time derivatives, to keep them constant all the time, would you use, rather than force these values to remain constant by introducing zero time derivatives (dTdt(1) = 0; , dTdt(nz+1) = 0;)? (In other words, would you please have any recommendations on how to keep the boundary values constant in the ODE solver without overwriting the time derivatives within the run of the algorithm?).
.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.--.-.-.-.-.-.-.-.-.-.-.-.-. CODE -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
% Simulation of a heat conduction % 24012023 clear all clc % Input parameters L = 1; % [m] t = 1; % [s] alfa = 0.1; % [degC/m] Ta = 80; % [degC] Tb = 20; % [degC] % Mesh nz = 20; dz = L/nz; % [m] % Initial conditions T0 = Tb*ones(1,nz+1); T0(1) = Ta; % Boundary condition/values for Z = 0 T0(nz+1) = Tb; % Boundary condition/values for Z = L z = linspace(0,L,nz+1); % ODE solver opts = odeset('RelTol',1e-4,'AbsTol',1e-5); % Ghost cell [time,T_ODE] = ode15s(@heat_calc, [0 t], T0, opts, nz, alfa, dz, Ta, Tb, 0); % dTdt = 0 [time2,T2_ODE] = ode15s(@heat_calc, [0 t], T0, opts, nz, alfa, dz, Ta, Tb, 1); % Plotting results subplot(2,1,1), plot(z,T_ODE),title('Ghost ODE') subplot(2,1,2), plot(z,T2_ODE),title('dTdt=0 ODE') %% function dTdt = heat_calc(t, T, nz, alfa, dz, Ta, Tb, parametr) % Add ghost cell % Boundary condition for Z = 0 and Z = L, is such implementation correct? Tg = [Ta; T; Tb]; dTdt = (alfa/dz^2).*(Tg(3:nz+3,1)... - 2.*Tg(2:nz+2,1) + Tg(1:nz+1,1)); % For keeping Ta and Tb constant, is such implementation correct? if parametr == 1 dTdt(1) = 0; dTdt(nz+1) = 0; end end 
submitted by iBo0m to matlab [link] [comments]


2023.01.22 15:39 iBo0m PDEs in MATLAB - controlling constant boundary values throughout the process

I am trying to solve a system of partial differential equations (PDEs) for a 1D flow (along Z-axis) with several phases defined by different boundary conditions (their duration is set by the simulation time of the phase).
.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- Problem description .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
At the beginning I define initial conditions (constant values) for t = 0, which I put in the resulting vector of unknown parameters. Next, I implement boundary conditions for the first phase for Z = 0 (Z = 0.5 for FVM) and Z = N (Z = N+0.5) and execute the ODE solver. The problem is that during time integration, the ODE solver overwrites the boundary values for Z = 0.5, which should remain constant.
After looking at the ODE solver in detail, it returns a non-zero values for the time derivatives of the variables for Z = 0.5 thus "changing" the boundary values. Arguably, the time derivatives calculation is not done correctly and returns non-zero values for the time derivatives on the Z = 0.5 boundary where the values are constant.
To "fix" this error, I have not found a better solution than to overwrite the time derivatives of the variables for Z = 0.5, after the ODE solver function has been computed, to zero values, thus achieving constant values at this boundary throughout all phases.
Principally, the algorithm should work by defining the time derivatives only once at the beginning and then changing only the boundary conditions, in my opinion.
Would you please have any recommendations on how to keep the boundary values constant in the ODE solver without overwriting the time derivatives within the run of the algorithm?
.-.-.-.-.-.-.-.-.-.-.-.- Numerical scheme and implementation of ICs and BCs .-.-.-.-.-.-.-.-.-.-.-.-.-
I use FVM and specify boundary conditions for the first and last walls of the finite volume (Z = 0.5 and Z = N+0.5, respectively).The initial conditions, at the beginning of my algorithm, are assigned to all central values of the finite volumes for time t = 0 for all N volumes.At the beginning of each phase, the boundary conditions are again assigned to the first and last walls, and the zeroing of the time derivates (likely a mistake) is performed for the initial finite volume centre Z = 1.
.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.- MATLAB example: my implementation .-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
Question: what computation (implementation), different to mine, of the initial boundary values (i.e. boundary conditions) and of these boundary values for all time derivatives to keep them constant all the time would you use, rather than force these values to remain constant by introducing zero time derivatives (dTdt(1) = 0; , dTdt(nz+1) = 0;).
.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.--.-.-.-.-.-.-.-.-.-.-.-.-. CODE -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
% Simulation of a heat conduction % 24012023 clear all clc % Input parameters L = 1; % [m] t = 1; % [s] alfa = 0.1; % [degC/m] Ta = 80; % [degC] Tb = 20; % [degC] % Mesh nz = 20; dz = L/nz; % [m] % Initial conditions T0 = Tb*ones(1,nz+1); T0(1) = Ta; % Boundary condition/values for Z = 0 T0(nz+1) = Tb; % Boundary condition/values for Z = L z = linspace(0,L,nz+1); % ODE solver opts = odeset('RelTol',1e-4,'AbsTol',1e-5); % Ghost cell [time,T_ODE] = ode15s(@heat_calc, [0 t], T0, opts, nz, alfa, dz, Ta, Tb, 0); % dTdt = 0 [time2,T2_ODE] = ode15s(@heat_calc, [0 t], T0, opts, nz, alfa, dz, Ta, Tb, 1); % Plotting results subplot(2,1,1), plot(z,T_ODE),title('Ghost ODE') subplot(2,1,2), plot(z,T2_ODE),title('dTdt=0 ODE') %% function dTdt = heat_calc(t, T, nz, alfa, dz, Ta, Tb, parametr) % Add ghost cell % Boundary condition for Z = 0 and Z = L, is such implementation correct? Tg = [Ta; T; Tb]; dTdt = (alfa/dz^2).*(Tg(3:nz+3,1)... - 2.*Tg(2:nz+2,1) + Tg(1:nz+1,1)); % For keeping Ta and Tb constant, is such implementation correct? if parametr == 1 dTdt(1) = 0; dTdt(nz+1) = 0; end end 
submitted by iBo0m to engineering [link] [comments]


2022.12.06 18:57 -hunter_117 Need help making Fourier series code for odd triangle function.

I'm trying to write a code for Fourier series for odd symmetric triangle function, but I'm facing some difficulties doing it. Here's what I'm trying to do: (I'm totally new to MATLAB so forgive me if what I'm doing is silly)
1- ao and an is zero because the function is odd so I'm not creating variables for them because they won't be in the formula.
2- t is => linspace(0, 4, 100); %I'll explain why I used such values at the end.
3- create an empty bn = []; and fx which is the sum of bn. fx = zeros(1, length(x));
4- create a for loop that from 1 to n and inside of it is:
for i = 1:n if mod(i, 2) == 1 bn = [bn; ((8/((pi^2) * (i^2))) * sin((i*pi*t)/2))]; fx = fx + ((8/((pi^2) * (i^2))) * sin((i*pi*t)/2)); end end figure subplot(2, 2, 1) plot(x, bn) xlabel('x') ylabel('f(x)') title('n') grid on subplot(2, 2, 3) plot(x, fx); xlabel('x') ylabel('f(x)') title('the sum of the functions') grid on 
The output of this code is not triangle function. I think my mistake is in the bn and fx but can't figure out what is it. I used the above values and order of code because we did the same in class for the square function and it worked successfully.
Any tips or hints would be appreciated.
Thanks.
submitted by -hunter_117 to matlab [link] [comments]


2022.11.25 06:59 itachi7898 how to plot impulse and unit step responses from bilinear transformation and Impulse invariant transformation

clc clear all close all num = [1 0]; den = [1 0.2] fs = 1 sys = bilinear(num,den,fs) subplot(2,1,1) step(sys) subplot(2,1,2) impulse(sys)
I am learning the matlab can someone please help me with this.
submitted by itachi7898 to matlab [link] [comments]


2022.11.24 07:19 hyfer14 Matplotlib hierarchy - Plotting 3D subplots using matplotlib

I am primarily a MATLAB user and used Python for many years. Only recently I have been trying to use matplotlib to plot 3D subplots - it took me over half a day to get what are pretty intuitive on MATLAB.
Is there a way to understand a hierarchy of the elements?
Thanks.
submitted by hyfer14 to learnpython [link] [comments]


2022.11.14 02:15 SatanWhoMeows Help with calling the Simulink Model

Help with calling the Simulink Model
For an assignment, I have written the following code. However, I'm having trouble to get a plot of the simulink model. (The code for Simulink is in the end)
Any feedback would be much appreciated. Thank you.
Code:

%Aircraft Parameters Al = 40,000; %Altitude; ft M = 0.900; %Mach TAS = 871; %True Air Speed; ft/s Pd = 222.8; %Dynamic Pressure; lb/ft^2 W = 636,636; %Weight; lb s = 5,500; %Wing Area; ft^2 b = 196; %Wing Span; ft c.bar = 27.3; %Wing Chord; ft CG = 0.25; %x*c.bar Alpha = 2.4; %Trim Angle of Attack; degree Ixxs = 1.82 * 10^7; %slug-ft^2 Iyys = 3.31 * 10^7; %slug-ft^2 Izzs = 4.97 * 10^7; %slug-ft^2 Ixzs = -3.50 * 10^5; %slug-ft^2 %Velocity U1 = 306.261; %m/s %Longitudinal Derivatives Xu = -0.0218; %1/s Xalp = 1.2227; %X alpha; ft/s^2 Zu = -0.0569; %1/s Zalp = -339.0036; %Z aplha; ft/s^2 Mu = -0.0001; %1/ft.s Malp = -1.6165; %M alpha; 1/s^2 Malpdot = -0.1425; %M alpha dot; 1/s Mq = -0.4038; %1/s Xde = 0; %X delta e; ft/s^2 Zde = -18.3410; %Z delta e; ft/s^2 Mde = -1.2124; %M delta e; 1/s^2 %Lateral Derivatives Yb = -55.7808; %Y beta; ft/s^2 Lb = -1.2555; %L beta; 1/s^2 Lp = -0.4758; %1/s Lr = 0.2974; %1/s Nb = 1.0143; %N beta; 1/s^2 Np = 0.0109; %1/s Nr = -0.1793; %1/s Ydr = 3.7187; %Y delta r; ft/s^2 Ldr = 0.2974; %L delta r; 1/s^2 Ndr = -0.4589; %N delta r; 1/s^2 Yda = 0; %Y delta a; ft/s^2 Lda = 0.1850; %L delta a; 1/s^2 Nda = -0.0135; %N delta a; 1/s^2 Abar = Ixzs/Ixxs; Bbar = Ixzs/Izzs; Ca = Ixzs/(Ixxs-(Ixzs^2/Izzs)); Da = 1/(1-(Ixzs^2/(Ixxs*Izzs))); %'0' Parameters Xtu = 0; Zq = 0; Mtu = 0; Theta1 = 0; Ntb = 0; Yp = 0; Yr = 0; Ntb = 0; Zalpdot = 0; %gravitational constant g = 9.81; %---------State Space Matrices for Longitudinal Dynamics---------- A = [Xu+Xtu Xalp 0 -g*cos(Theta1); (Zu/(U1-Zalpdot)) (Zalp/(U1-Zalpdot)) ((Zq+U1)/(U1-Zalpdot)) ((-g*sin(Theta1))/(U1-Zalpdot)); Mu+Mtu+((Malpdot*Zu)/(U1-Zalpdot)) Malp+((Malpdot*Zalp)/(U1-Zalpdot)) Mq+(Malpdot*(U1+Zq)/(U1-Zalpdot)) (Malpdot*g*sin(Theta1)/(U1-Zalpdot)); 0 0 1 0] B = [Xde; (Zde/(U1-Zalpdot)); Mde+((Malpdot*Zde)/(U1-Zalpdot)); 0] C = [1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1] D = [0;0;0;0] %Transfer Functions (Longitudinal) and their plots (using subplots) %Input: Elevator Deflection %Forward Velocity(U1)/Del [Num1, Den] = ss2tf(A, B, C, D,1); TF1= tf(Num1(1,:),Den) figure ('Name','Longitudinal TF Plots','NumberTitle','off') disp ('Longitudinal TF Plots'); subplot (411) TF1S = step(TF1) plot(TF1S) xlabel ('X') ylabel ('Y') title ('U vs Del') %Angle of Attack/Del [Num2, Den] = ss2tf(A, B, C, D,1); TF2 = tf(Num2(2,:),Den) subplot (412) TF2S = step(TF2) plot(TF2S) xlabel ('X') ylabel ('Y') title ('Alpha vs Del') %Pitch Rate/Del [Num3, Den] = ss2tf(A, B, C, D,1); TF3 = tf(Num3(3,:),Den) subplot (413) TF3S = step(TF3) plot(TF3S) xlabel ('X') ylabel ('Y') title ('Alpha vs Del') %Pitch Angle/Del [Num4, Den] = ss2tf(A, B, C, D,1); TF4 = tf(Num4(4,:),Den) subplot (414) TF4S = step(TF4) plot(TF4S) xlabel ('X') ylabel ('Y') title ('Alpha vs Del') %----------Lateral State Space Matrices---------- A1 = [Yb/U1 Yp/U1 (Yr-U1)/U1 g*cos(Theta1) 0; (Lb+Ca)*((Nb+Ntb+Bbar)*Lb) ((Lp+Ca)*(Bbar*Lp)) (Lr+Ca*Nr+Bbar*Lr) 0 0; Da*Nb+Ntb+Bbar*Lb Da*Bbar*Lp Da*Nr+Bbar*Lr 0 0; 0 1 0 0 0; 0 0 1 0 0] B1 = [Yda/U1 YdU1; Lda+Ca*Nda+Bbar*Lda Ldr+Ca*Ndr+Bbar*Ldr; Da*Nda+Bbar*Lda Da*Ndr+Bbar*Ldr; 0 0; 0 0] C1 = [1 0 0 0 0; 0 1 0 0 0; 0 0 1 0 0; 0 0 0 1 0; 0 0 0 0 1] D1 = [0 0; 0 0; 0 0; 0 0; 0 0] %Transfer Functions (Lateral) and their plots (using individual plots) %Input: Aileron Deflection %Side Slip Angle/Dela [Num01, Den1] = ss2tf(A1, B1, C1, D1,1); TF1Lateral = tf(Num01(1,:),Den1) figure ('Name','Lateral TF1 Plot','NumberTitle','off') disp ('Lateral TF1 Plot') step_1 = step(TF1Lateral) plot(step_1) xlabel('X') ylabel('Y') title('Side Slip Angle/Aileron Deflection') %Roll Rate/Dela [Num02, Den1] = ss2tf(A1, B1, C1, D1,1); TF2Lateral = tf(Num02(2,:),Den1) figure ('Name','Lateral TF2 Plot','NumberTitle','off') disp ('Lateral TF2 Plot') step_2 = step(TF2Lateral) plot(step_2) xlabel('X') ylabel('Y') title('Roll Rate/Aileron Deflection') %Yaw Rate/Dela [Num03, Den1] = ss2tf(A1, B1, C1, D1,1); TF3Lateral = tf(Num03(3,:),Den1) figure ('Name','Lateral TF3 Plot','NumberTitle','off') disp ('Lateral TF3 Plot') step_3 = step(TF3Lateral) plot(step_3) xlabel('X') ylabel('Y') title('Yaw Rate/Aileron Deflection') %Roll Angle/Dela [Num04, Den1] = ss2tf(A1, B1, C1, D1,1); TF4Lateral = tf(Num04(4,:),Den1) figure ('Name','Lateral TF4 Plot','NumberTitle','off') disp ('Lateral TF4 Plot') step_4 = step(TF4Lateral) plot(step_4) xlabel('X') ylabel('Y') title('Roll Angle/Aileron Deflection') %Yaw Angle/Dela [Num05, Den1] = ss2tf(A1, B1, C1, D1,1); TF5Lateral = tf(Num05(5,:),Den1) figure ('Name','Lateral TF5 Plot','NumberTitle','off') disp ('Lateral TF5 Plot') step_5 = step(TF5Lateral) plot(step_5) xlabel('X') ylabel('Y') title('Yaw Angle/Aileron Deflection') %Input: Rudder Deflection %Side Slip Angle/Delr [Num01, Den2] = ss2tf(A1, B1, C1, D1,2); TF6Lateral = tf(Num01(1,:),Den2) figure ('Name','Lateral TF6 Plot','NumberTitle','off') disp ('Lateral TF6 Plot') step_6 = step(TF6Lateral) plot(step_6) xlabel('X') ylabel('Y') title('Side Slip Angle/Rudder Deflection') %Roll Rate/Delr [Num02, Den2] = ss2tf(A1, B1, C1, D1,2); TF7Lateral = tf(Num02(2,:),Den2) figure ('Name','Lateral TF7 Plot','NumberTitle','off') disp ('Lateral TF7 Plot') step_7 = step(TF7Lateral) plot(step_7) xlabel('X') ylabel('Y') title('Roll Rate/Rudder Deflection') %Yaw Rate/Delr [Num03, Den2] = ss2tf(A1, B1, C1, D1,2); TF8Lateral = tf(Num03(3,:),Den2) figure ('Name','Lateral TF8 Plot','NumberTitle','off') disp ('Lateral TF8 Plot') step_8 = step(TF8Lateral) plot(step_8) xlabel('X') ylabel('Y') title('Yaw Rate/Rudder Deflection') %Roll Angle/Delr [Num04, Den2] = ss2tf(A1, B1, C1, D1,2); TF9Lateral = tf(Num04(4,:),Den2) figure ('Name','Lateral TF9 Plot','NumberTitle','off') disp ('Lateral TF9 Plot') step_9 = step(TF9Lateral) plot(step_9) xlabel('X') ylabel('Y') title('Roll Angle/Rudder Deflection') %Yaw Angle/Delr [Num05, Den2] = ss2tf(A1, B1, C1, D1,2); TF10Lateral = tf(Num05(5,:),Den2) figure ('Name','Lateral TF10 Plot','NumberTitle','off') disp ('Lateral TF10 Plot') step_10 = step(TF10Lateral) plot(step_10) xlabel('X') ylabel('Y') title('Yaw Angle/Rudder Deflection') %----------For Simulink---------- %Longitudinal simtime = 50; gain = 1; u = 1; X0 = 0; %Initial Condition load_system('Simulink_Longitudinal_SA3.slx') data = sim('Simulink_Longitudinal_SA3.slx') plot(data); I am attaching a screenshot of what my simulink model looks like and the error I am getting on MATLAB.


https://preview.redd.it/4ds7q4b4itz91.png?width=868&format=png&auto=webp&s=d791b5075c12c88d42de388724c6b7427916a8af

https://preview.redd.it/c2xhkwr2itz91.png?width=1440&format=png&auto=webp&s=11ce247ff757c9456cb09467e2472c6a067a7b0a
submitted by SatanWhoMeows to matlab [link] [comments]


2022.10.31 15:48 slowdiivnothing How to integrate MIMO detector code into Bluetooth BER simulation code

How to integrate MIMO detector code into Bluetooth BER simulation code
Hi im doing a bluetooth project using bluetooth toolbox of that in MATLAB. I'm trying to add MIMO detector in the Rx part of bluetooth simulation. The main code is from example code provided in MATLAB(https://www.mathworks.com/help/bluetooth/ug/noncollaborative-coexistence-modeling-between-bluetooth-br-edr-le-and-wlan-networks.html) Now I want to add MIMO part into the main code. I've coded MIMO part but I have no idea how to integrate this part of my code into the main code of the simulation.
Block diagram of the bluetooth main code(simulation)
Below is the my code implementing MIMO detector:
%MIMO Detector using LMS Algorithm clc; clear all; close all; sam = 1/2.4e11; t=1/2.4e11:sam:10/2.4e9; %time a=2; %number of antennas des=sin(2pi(2.4*109)*t); %desired signal with frequency of 2.4GHz n=numel(des); %number of elements of desired signal %received signal with noise for i=1:a des_phase = sin(2pi(2.4e9)t+360rand); for j=1:n rec(i,j)=des_phase(j)+0.4*randn; end end y = []; conmax = []; rec_fix=[]; for i = 1:a rec_dummy = rec(i,:); con = conv(des,rec_dummy); conmax(i) = max(con); y(i) = find(con == max(con))-n; rec_f=circshift(rec_dummy,-y(i)); rec_fix=[rec_fix;rec_f]; end plot(rec_fix'); iter = 1000; E=[]; %error matrix w=zeros(1,a); %weight vector mu=0.005; %mu parameter %LMS argorithm iteration for j=a:n for k = 1:iter for i=1:a E(i,j)=des(j)-w(i)rec_fix(i,j); %E=d-X'W w(i)=w(i)+2muE(i,j)rec_fix(i,j); %w_j+1=w+j+2muE_j*X_j end end est(j)=sum(w(i)*rec_fix(i,j)); end err = est-des; snr = snr(des,err); figure; subplot(4,1,1),plot(des),ylim([-1.5,1.5]); title('desired signal'); subplot(4,1,2),plot(rec'),ylim([-1.5,1.5]); title('received signal'); subplot(4,1,3),plot(est),ylim([-1.5,1.5]); title('estimated signal'); subplot(4,1,4),plot(err),ylim([-1.5,1.5]); title('error signal'); 
I think the corresponding part of the main code is:
% Recover the data bits if any(strcmp(awnSignalType,["LE1M","LE2M","LE500K","LE125K"])) rxCfg.ChannelIndex = channelIndex; [rxBits,accAddress] = helperBLEPracticalReceiver(filteredWaveform,rxCfg); if isempty(rxBits) ~isequal(accessAddBits,accAddress) pktStatus = []; end else % Get PHY properties rxCfg.WhitenInitialization = awnWaveformConfig.WhitenInitialization; [rxBits,~,pktStatus]... = helperBluetoothPracticalReceiver(filteredWaveform,rxCfg); end 
How can I modify the main code to add MIMO part so that the BER performance would get better? Thanks :)
submitted by slowdiivnothing to DSP [link] [comments]


2022.10.27 19:36 laurosaurus_rex How to add name-value pairs without a default value when defining a function

I'm creating a function to plot data from a spreadsheet. I'd like to have optional variables using name-value pairs and if they aren't defined by the user leave the variable empty. The only thing I can find is addOptional, but that requires a default value. I have some ideas for a workaround (making the default value something crazy and checking if the variable is that instead of if it exists) but would like something cleaner.

The name-value pairs I'd like to have are the name of the folder, which might not be needed if the spreadsheet is in the same folder as the program, figure name or number if there is already a figure that the user wants the plot to be on, and subplot position if they want it in a specific spot in a preexisting subplot. This is for my senior Capstone project and we need to plot data from multiple rounds of testing and want to have the option to use the function in a variety of contexts.
submitted by laurosaurus_rex to matlab [link] [comments]


2022.10.24 02:18 hans-hearth Increasing the size of subplots

Increasing the size of subplots
I could not apply some of the soultions I found on MATLAB Answers, so I am asking here.
I have the following 2x3 subplot
I am trying to increase the size of the images and reduce the amount of whitespace in the maximized figure window.

Any help appreciated
Code---
 figure; subplot(2, 3, 1); imshow((An{1})); title('$A_{50}$',FontSize=16,Interpreter='latex') subplot(2, 3, 2); imshow((An{2})); title('$A_{100}$',FontSize=16,Interpreter='latex') subplot(2, 3, 3); imshow((An{3})); title('$A_{200}$',FontSize=16,Interpreter='latex') subplot(2, 3, 4); imshow((An{4})); title('$A_{300}$',FontSize=16,Interpreter='latex') subplot(2, 3, 5); imshow((An{5})); title('$A_{400}$',FontSize=16,Interpreter='latex') subplot(2, 3, 6); imshow((An{5})); title('Original',FontSize=16,Interpreter='latex') sgtitle('The title',FontSize=16,Interpreter='latex') 

https://preview.redd.it/3sq1b2nncnv91.png?width=1919&format=png&auto=webp&s=18ebe4a26839811bab7a1dcc5bdcbb4042358c56
submitted by hans-hearth to matlab [link] [comments]


2022.10.06 01:10 Drezkul how do I fix this chart it says if it is a rainbow then it's wrong. what do I ND to change for script.

how do I fix this chart it says if it is a rainbow then it's wrong. what do I ND to change for script. submitted by Drezkul to matlab [link] [comments]


2022.09.24 10:06 notafuckingvalue Minor errors in my code that I cannot figure out...

I am trying to plot a discrete-time signal for my labwork but I have encountered a few minor problems.
n = 0:1:127; %Increment from 0 to 127 by 1 (discrete time) x1 = cos(0.14*pi*n); figure(1); title('Discrete Time Signal for x1[n]=cos[0.14\pin]') xlabel('n'); ylabel('x1[n]'); stem(n,x1,"filled"); % To plot discrete data writematrix(x1,"x1data.xls"); M = readmatrix(x1,"x1data.xls"); disp("x displays" + M(1,[2 8 111 127])) fprintf('x1(2)= %f\n', x1(2)); fprintf('x1(8)= %f\n', x1(8)); fprintf('x1(111)= %f\n', x1(111)); fprintf('x1(127)= %f\n', x1(127)); 
I can get the desired plot but:
  1. Matlab is giving me an error for this line M = readmatrix(x1,"x1data.xls");
  2. No matter what I do I cannot get axis labels and title for my plot. If I play around with the position of the stem line then either it only shows axis labels and title with no plot or if it is in the current position then it just shows the discrete-time plot.
  3. Also I have another similar plot for a slightly different function that isn't showing up at all. Its .xls file isn't being generated for some reason.

x2 = cos(2.3*pi*n); figure(2); subplot(2,1,1); title('Discrete Time Signal for x2[n] = cos[2.3\pin]'); xlabel('n'); ylabel('x2[n]'); stem(n,x2,'filled'); % To plot discrete data writematrix(x2, "x2data.xls"); M = readmatrix(x2, "x2data.xls"); disp("x displays " + M(1,[2 8 111 127])) fprintf('\n'); fprintf('\n'); fprintf('x2(2) = %f\n', x2(2)); fprintf('x2(8) = %f\n', x2(8)); fprintf('x2(111) = %f\n', x2(111)); fprintf('x2(127) = %f\n', x2(127)); 
^This code block is just after the previous one. So how can I fix these minor issues. As you can tell I am fairly new to Matlab so any help would be much appreciated!
submitted by notafuckingvalue to matlab [link] [comments]


2022.09.17 08:17 Various_Analysis14 Error in figure window

Error in figure window
I am trying to resize an image in MATLAB. The size of the image is changing but it's not showing the resized image in the figure window. Could use some help pls!!

https://preview.redd.it/49tewwwn4do91.png?width=1603&format=png&auto=webp&s=668923e56647b0ae5c752237f3bcb3b956c421b8

submitted by Various_Analysis14 to matlab [link] [comments]


2022.09.07 19:52 Drezkul Error using plot vectors must be same length

Error using plot vectors must be same length submitted by Drezkul to matlab [link] [comments]


2022.05.27 19:55 mechanicalraspberry Carrier Synchronization Loop Filter - what does 'T' mean?

I have implemented my own carrier synchronizer function based off of the algorithm from this Matlab page:
https://uk.mathworks.com/help/comm/ref/comm.carriersynchronizer-system-object.html#bultrxw-19
My code works, however, the Loop Bandwidth (Bn*T) that is prescribed in the documentation does not work for me. Instead I am using Bn * T = 0.005. I came across this value purely by chance, and I am not sure why it is that...
Matlab's default value is Bn = 0.01.
I assumed T = 1 / symbol rate, since this is not explained on the page. The symbol rate in my simulation is 36e6 Sym/s, so I assume T = 2.7778e-8.
Using these assumptions, Bn * T = 2.777e-10, which is orders of magnitudes away from my working value of 0.005.
So my question is, what is T?
If I reverse the equation from my working Bn * T = 0.005, with Bn = 0.01, then T = 0.5, but what does T = 0.5 mean?
Here is my code, with Bn and T set to my working values:
close all rng(41) sample_rate = 36e6; nSym = 15000; nBit = nSym*2; nMap = nBit / nSym; %% Create bits and modulate them to QPSK bits = randi([0 1], nSym, nMap); sym0 = 2^-0.5 + 1j*2^-0.5; sym1 = -2^-0.5 + 1j*2^-0.5; sym2 = 2^-0.5 - 1j*2^-0.5; sym3 = -2^-0.5 - 1j*2^-0.5; syms = zeros(nSym, 1); for loop = 1:nSym if bits(loop,:) == [0,0] syms(loop, 1) = sym0; elseif bits(loop,:) == [0, 1] syms(loop, 1) = sym1; elseif bits(loop,:) == [1, 0] syms(loop, 1) = sym2; elseif bits(loop,:) == [1, 1] syms(loop, 1) = sym3; end end %% Add Noise xn = awgn(syms, 20); scatterplot(xn) title('Sybmbols with Noise') %% Freq and Phase Offset pfo = comm.PhaseFrequencyOffset('PhaseOffset',45,'FrequencyOffset',1e5, ... 'SampleRate',sample_rate); xn = pfo(xn); scatterplot(xn) title('Sybmbols with Noise and Phase and Frequency Offset') %% Create Arrays yn = zeros(nSym, 1); yn_rot = zeros(nSym, 1); en = zeros(nSym, 1); psin = zeros(nSym, 1); lambdan = zeros(nSym, 1); demod_s = zeros(nSym, 2); lambda = 0; %% Algorithm Values T = 0.5; % WHAT DOES THIS MEAN? Bn = 0.01; % WHAT DOES THIS MEAN? zeta = 0.707; % damping factor K0 = 1; Kp = 2; omega = (Bn * T) / (zeta + (1 / (4*zeta))); d = 1 + (2 * zeta * omega) + omega^2; gi = (4 * (omega^2) / d) / (Kp * K0); gp = (4 * zeta * omega / d) / (Kp * K0); %% Loop over the incoming symbols for loop = 1:nSym %% Phase Shift yn(loop, 1) = xn(loop) * exp( 1i * lambda ); y = yn(loop, 1); %% Rotate the output to correct positions % This needs to be replaced by another function that rotates % automatically based on Start Of Frame or Pilots % This value works with current SNR and RNG seed yn_rot(loop, 1) = y * exp(1i * 3*pi/4) * -1; y_rot = yn_rot(loop, 1); %% Phase Error Detector en(loop,1) = sign(real(yn(loop,1))) * imag(yn(loop,1))... - sign(imag(yn(loop,1))) * real(yn(loop,1)); e = en(loop, 1); %% Loop Filter Starting Values % psi_1 is previous psi % en_1 is previous em if loop == 1 psi_1 = 0; en_1 = 0; lambdan_1 = 0; else psi_1 = psin(loop-1, 1); en_1 = en(loop-1, 1); lambdan_1 = lambdan(loop-1, 1); end psin(loop, 1) = gi * en(loop,1) + psi_1; psi = psin(loop, 1); %% DDS lambdan(loop, 1) = (gp * en_1 + psi_1) + lambdan_1; lambda = lambdan(loop, 1); %% Hard Demodulate if real(y_rot) > 0 && imag(y_rot) > 0 demod_s(loop,:) = [0, 0]; elseif real(y_rot) < 0 && imag(y_rot) > 0 demod_s(loop,:) = [0, 1]; elseif real(y_rot) > 0 && imag(y_rot) < 0 demod_s(loop,:) = [1, 0]; elseif real(y_rot) < 0 && imag(y_rot) < 0 demod_s(loop,:) = [1, 1]; end end %% Results figure() subplot(3, 1, 1) plot(en) title('Phase Error Detector') subplot(3, 1, 2) plot(psin) title('Loop Filter Output') subplot(3, 1, 3) plot(lambdan) title('DDS Output') xlabel('Time (Symbols)') [~, ber] = biterr(bits(end-1000:end,:), demod_s(end-1000:end,:)) ber = 0 scatterplot(yn_rot(end-10000:end, :)) title('Carrier Synchronized Output') 
submitted by mechanicalraspberry to matlab [link] [comments]


2022.05.07 12:57 code_hunter_cc Parallel Coordinates plot in Matplotlib

Python
Two and three dimensional data can be viewed relatively straight-forwardly using traditional plot types. Even with four dimensional data, we can often find a way to display the data. Dimensions above four, though, become increasingly difficult to display. Fortunately, parallel coordinates plots provide a mechanism for viewing results with higher dimensions.
![Example Parallel Coordinates Plot from Wikipedia](https://upload.wikimedia.org/wikipedia/en/4/4a/ParCorFisherIris.png)
Several plotting packages provide parallel coordinates plots, such as Matlab, R, VTK type 1 and VTK type 2, but I don't see how to create one using Matplotlib.
  1. Is there a built-in parallel coordinates plot in Matplotlib? I certainly don't see one in the gallery.
  2. If there is no built-in-type, is it possible to build a parallel coordinates plot using standard features of Matplotlib?
Edit:
Based on the answer provided by Zhenya below, I developed the following generalization that supports an arbitrary number of axes. Following the plot style of the example I posted in the original question above, each axis gets its own scale. I accomplished this by normalizing the data at each axis point and making the axes have a range of 0 to 1. I then go back and apply labels to each tick-mark that give the correct value at that intercept.
The function works by accepting an iterable of data sets. Each data set is considered a set of points where each point lies on a different axis. The example in __main__ grabs random numbers for each axis in two sets of 30 lines. The lines are random within ranges that cause clustering of lines; a behavior I wanted to verify.
This solution isn't as good as a built-in solution since you have odd mouse behavior and I'm faking the data ranges through labels, but until Matplotlib adds a built-in solution, it's acceptable.
```

!/usbin/pythonimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerdef parallel_coordinates(data_sets, style=None): dims = len(datasets[0]) x = range(dims) fig, axes = plt.subplots(1, dims-1, sharey=False) if style is None: style = ['r-']len(data_sets) # Calculate the limits on the data min_max_range = list() for m in zip(data_sets): mn = min(m) mx = max(m) if mn == mx: mn -= 0.5 mx = mn + 1. r = float(mx - mn) min_max_range.append((mn, mx, r)) # Normalize the data sets norm_data_sets = list() for ds in data_sets: nds = [(value - min_max_range[dimension][0]) / min_max_range[dimension][2] for dimension,value in enumerate(ds)] norm_data_sets.append(nds) data_sets = norm_data_sets # Plot the datasets on all the subplots for i, ax in enumerate(axes): for dsi, d in enumerate(data_sets): ax.plot(x, d, style[dsi]) ax.set_xlim([x[i], x[i+1]]) # Set the x axis ticks for dimension, (axx,xx) in enumerate(zip(axes, x[:-1])): axx.xaxis.set_major_locator(ticker.FixedLocator([xx])) ticks = len(axx.get_yticklabels()) labels = list() step = min_max_range[dimension][2] / (ticks - 1) mn = min_max_range[dimension][0] for i in xrange(ticks): v = mn + istep labels.append('%4.2f' % v) axx.set_yticklabels(labels) # Move the final axis' ticks to the right-hand side axx = plt.twinx(axes[-1]) dimension += 1 axx.xaxis.set_major_locator(ticker.FixedLocator([x[-2], x[-1]])) ticks = len(axx.get_yticklabels()) step = min_max_range[dimension][2] / (ticks - 1) mn = min_max_range[dimension][0] labels = ['%4.2f' % (mn + istep) for i in xrange(ticks)] axx.set_yticklabels(labels) # Stack the subplots plt.subplots_adjust(wspace=0) return pltif __name_ == '__main__': import random base = [0, 0, 5, 5, 0] scale = [1.5, 2., 1.0, 2., 2.] data = [[base[x] + random.uniform(0., 1.)scale[x] for x in xrange(5)] for y in xrange(30)] colors = ['r'] * 30 base = [3, 6, 0, 1, 3] scale = [1.5, 2., 2.5, 2., 2.] data.extend([[base[x] + random.uniform(0., 1.)scale[x] for x in xrange(5)] for y in xrange(30)]) colors.extend(['b'] * 30) parallel_coordinates(data, style=colors).show()

``` Edit 2:
Here is an example of what comes out of the above code when plotting Fisher's Iris data. It isn't quite as nice as the reference image from Wikipedia, but it is passable if all you have is Matplotlib and you need multi-dimensional plots.
![Example result of parallel coordinates plot from this answer](https://i.stack.imgur.com/N1mpi.png)
Answer link : https://codehunter.cc/a/python/parallel-coordinates-plot-in-matplotlib
submitted by code_hunter_cc to codehunter [link] [comments]


2022.05.04 22:15 Sr_Leckie Advise needed: I'm transitioning from Matlab into Python and I can't plot simple range values!

Hello Everyone!
I'm working on leaving Matlab behind and move into Python, and I was working on a basic code where I'm trying to plot a range of values, but I keep getting error after error and I'm unsure why. I'm basically new at Python, the value ranges seen below were done after some research on how to do them, but basically here's the coding issue I'm facing:
The Matlab code is:
P1 = 0.101325:-0.0012265:0.040; G2 = 1:0.006:1.3; R1 = 1:0.05:3.5; C_P1 = (P1).*(1+0.5.*(G2-1).*R1.^2).^(G2/(2-1)); plot(R1,C_P1) title('Plot Title') xlabel('X label') ylabel('Y label') 
But, when transitioning into Python I just can't get it right. Am I over-complicating things?
import numpy as np import matplotlib.pyplot as plt import math start = 0.101325 stop = 0.040 step = -0.006 P1 = np.arange(start, stop+step, step) start2 = 1 stop2 = 1.3 step2 = 0.006 G = np.arange(start2, stop2+step2, step2) start3 = 1 stop3 = 3.5 step3 = 0.05 R1 = np.arange(start3, stop3+step3, step3) C_P1 = (P1)*(1+0.5*(G-1)*R1**2)**(G/(G-1)) fig, ax=plt.subplots(figsize=(12,6)) ax.plot(C_P1, color='blue', label='Combustion chamber') ERROR: ValueError: operands could not be broadcast together with shapes (52,) (51,) 
The Matrix size does match in Matlab, so I think it should also be valid in python.
How can I make it work?

Please advise,
Thanks!

EDIT: I added the import libraries into the code, and the code portion for the plot.
submitted by Sr_Leckie to learnpython [link] [comments]


2022.04.20 21:47 neil51801 homework question

I don't currently have access to my Matlab but for this homework question, I got stuck using the two nested for loops since I kept trying to do an if-then loop. if I can have an example nested for loop with thresholds and colors then I would be super grateful! thank you! also please let me know if any of you want anything else from my end, i can upload my work later if that helps!
Write a script file that will accomplish the following: a) Bring in the data associated with the image "zippy.jpg" available on Brightspace. b) Prompt the user to enter 3 values: a. A threshold value for the red channel (must be an integer value between 0-255) b. A threshold value for the green channel (must be an integer value between 0-255) c. A threshold value for the blue channel (must be an integer value between 0-255) c) Using 2 nested for loops: a. Evaluate each pixel's R,G,B value b. If the pixel's R value is greater than the user's threshold value for Red, set that value equal to the threshold instead c. If the pixel's R value is less than or equal to the threshold value for Red, leave it alone (nothing changes) d. Do this for each pixel's Green and Blue intensity values d) Create a 2x2 subplot where you plot all the following images in the same figure window: a. In the top-left corner, display the original image b. In the top-right corner, display the image with only the RED channel modified by the loop (green and blue remain untouched) c. In the bottom-left corner, display the image when both the RED channel and GREEN channels have been modified by the loop (but blue remains untouched) d. In the bottom-right corner, display the image when ALL COLOR CHANNELS have been modified by the loop
submitted by neil51801 to matlab [link] [comments]


2022.03.16 06:28 code_hunter_cc Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Python
I'm familiar with the following questions:
Matplotlib savefig with a legend outside the plot
How to put the legend out of the plot
It seems that the answers in these questions have the luxury of being able to fiddle with the exact shrinking of the axis so that the legend fits.
Shrinking the axes, however, is not an ideal solution because it makes the data smaller making it actually more difficult to interpret; particularly when its complex and there are lots of things going on ... hence needing a large legend
The example of a complex legend in the documentation demonstrates the need for this because the legend in their plot actually completely obscures multiple data points.
http://matplotlib.sourceforge.net/users/legend_guide.html#legend-of-complex-plots
What I would like to be able to do is dynamically expand the size of the figure box to accommodate the expanding figure legend.
import matplotlib.pyplot as pltimport numpy as npx = np.arange(-2*np.pi, 2*np.pi, 0.1)fig = plt.figure(1)ax = fig.add_subplot(111)ax.plot(x, np.sin(x), label='Sine')ax.plot(x, np.cos(x), label='Cosine')ax.plot(x, np.arctan(x), label='Inverse tan')lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))ax.grid('on') Notice how the final label 'Inverse tan' is actually outside the figure box (and looks badly cutoff - not publication quality!)![enter image description here](https://i.stack.imgur.com/0XtO2.png)
Finally, I've been told that this is normal behaviour in R and LaTeX, so I'm a little confused why this is so difficult in python... Is there a historical reason? Is Matlab equally poor on this matter?
I have the (only slightly) longer version of this code on pastebin http://pastebin.com/grVjc007
Answer link : https://codehunter.cc/a/python/moving-matplotlib-legend-outside-of-the-axis-makes-it-cutoff-by-the-figure-box
submitted by code_hunter_cc to codehunter [link] [comments]