Month: June 2024
Bug with entra shared IOS and teams?
Have IPhones setup using the entra shared mode, everything works great at a base level. Devices get configured to be in shared mode, sso works like a charm for edge and the first user into teams, device gets that user logged out and next user signs in, again edge detects and user is signed in but when you open a teams it’s looking for a email address, if you force close teams it triggers the sso extension and the user gets logged in. Cannot for the life of me figure out why teams ends up in a state where it’s logged out but unable to gets the user creds passed to it. This was not an issue in the past. A reminder this is not iPad shared mode I’m talking about, people get them confused.
Have IPhones setup using the entra shared mode, everything works great at a base level. Devices get configured to be in shared mode, sso works like a charm for edge and the first user into teams, device gets that user logged out and next user signs in, again edge detects and user is signed in but when you open a teams it’s looking for a email address, if you force close teams it triggers the sso extension and the user gets logged in. Cannot for the life of me figure out why teams ends up in a state where it’s logged out but unable to gets the user creds passed to it. This was not an issue in the past. A reminder this is not iPad shared mode I’m talking about, people get them confused. Read More
Assigning a line plot object to a global property doesn’t retain it after the object is deleted
Is there a reason why when I delete a plot of a multiplot graph and assign it to a global (public) property it doesn’t retain it.
ax=app.UIAxes; % My plot is on a UIAxes
t = ax.Children(1) % Get the last plot
app.myPlot=t % myPlot is a Global property
delete(t);
app.myPlot
app.myPlot shows:
ans =
handle to deleted Line
so instead I have to access all the properties of the line individually and assign to a struct.
s = struct;
s.X=t.XData;
s.Y=t.YData;
s.Cl=t.Color;
s.DN=t.DisplayName;
s.Ls=t.LineStyle;
s.Lw=t.LineWidth
s.M=t.Marker;
app.myPlot=s;
Just seems more clunky!Is there a reason why when I delete a plot of a multiplot graph and assign it to a global (public) property it doesn’t retain it.
ax=app.UIAxes; % My plot is on a UIAxes
t = ax.Children(1) % Get the last plot
app.myPlot=t % myPlot is a Global property
delete(t);
app.myPlot
app.myPlot shows:
ans =
handle to deleted Line
so instead I have to access all the properties of the line individually and assign to a struct.
s = struct;
s.X=t.XData;
s.Y=t.YData;
s.Cl=t.Color;
s.DN=t.DisplayName;
s.Ls=t.LineStyle;
s.Lw=t.LineWidth
s.M=t.Marker;
app.myPlot=s;
Just seems more clunky! Is there a reason why when I delete a plot of a multiplot graph and assign it to a global (public) property it doesn’t retain it.
ax=app.UIAxes; % My plot is on a UIAxes
t = ax.Children(1) % Get the last plot
app.myPlot=t % myPlot is a Global property
delete(t);
app.myPlot
app.myPlot shows:
ans =
handle to deleted Line
so instead I have to access all the properties of the line individually and assign to a struct.
s = struct;
s.X=t.XData;
s.Y=t.YData;
s.Cl=t.Color;
s.DN=t.DisplayName;
s.Ls=t.LineStyle;
s.Lw=t.LineWidth
s.M=t.Marker;
app.myPlot=s;
Just seems more clunky! plot, struct, property MATLAB Answers — New Questions
ive been trying to generate vhdl code using hdl code genrator on matlab 2020a but its showing error regarding the use of fi in my code , can someone fix it for me ? thankyou
this is my code : MATLAB FUNCTION
function [received_signal_real, received_signal_imag, error_rate] = hdl_compatible_code(n, channel_type)
% Constants
aircraft_altitude = fi(45000,1,32,10); % Altitude of the aircraft in feet
distance_km = fi(350,1,32,10); % Distance between aircraft and base station in kilometers
speed_of_light = fi(3e8,1,32,10); % Speed of light in m/s
n = 100;
% Pathloss model – Free Space Path Loss (FSPL)
fc = fi(1.5e9,1,32,10); % Carrier frequency in Hz (1.5GHz)
lambda = speed_of_light / fc; % Wavelength
path_loss_dB = 20 *log10_approx(fi(4 * pi * distance_km * 1e3 / lambda,1,32,10)); % Path loss in dB
% AWGN
SNR_dB_awgn = fi(10,1,32,10); % Signal to noise ratio in dB for AWGN channel
SNR_awgn = fi(fi(10)^(SNR_dB_awgn / 10),1,32,10); % Convert SNR to linear scale for AWGN channel
tx_power_awgn = fi(1,1,32,10); % Initial guess for transmit power for AWGN channel
noise_power_awgn = tx_power_awgn / SNR_awgn; % Noise power based on SNR for AWGN channel
% Doppler spread
aircraft_speed = fi(660,1,32,10); % Average aircraft speed in meters per second
fd_max = fi(((aircraft_speed * fi(0.51444,1,32,10) * fc) / speed_of_light),1,32,10); % Doppler frequency shift
% Modulation using lookup table
% Precompute constellation points (Scalar approach)
constellation_points = [fi(1,1,16,10), fi(1i,1,16,10),fi(-1,1,16,10), fi(-1i,1,16,10)];
% Modulation
data = lfsr_data(n); % Generate random bits
qpsk_symbols = constellation_points(data + 1); % QPSK modulation: symbol mapping to complex constellation points
% Generate doppler effect using lookup table
two_pi_fd_max = fi(2*pi*fd_max,1,128,10);
t = fi((0:n-1) /n,1,32,10); % Time vector
doppler_shift = cos_lookup(fi((2 * pi * fd_max * t),1,32,10));
% Channel simulation
if channel_type == 0 % AWGN channel
noise_real = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for real part
noise_imag = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for imaginary part
received_signal = (qpsk_symbols .* doppler_shift) + noise_real + fi(1i,1,16,10) * noise_imag; % Received signal in AWGN channel
elseif channel_type == 1 % Rician fading channel
% Rician channel parameters
K =fi( 5,1,32,10); % Rician factor
LOS_power_dB =fi( -10,1,32,10); % Line of sight power in dB
LOS_power_linear = pow2(fi(10,1,32,10),LOS_power_dB/10); % Convert LOS power to linear scale
K_linear = pow2(fi(10,1,32,10),K/10); % Convert Rician factor to linear scale
% Generate fading coefficients
LOS = sqrt(LOS_power_linear / (2 * (1 + 1 / K_linear))) * ones(1, n,’like’,fi(0,1,16,10)); % LOS component
scattering = sqrt(LOS_power_linear / (2 * (1 + K_linear))) * (lfsr_noise(n) +fi( 1i,1,16,10) * lfsr_noise(n)); % Scattering component
fading_coefficient = LOS + scattering; % Rician fading coefficients
received_signal = (qpsk_symbols .* fading_coefficient .* doppler_shift); % Apply fading to the transmitted signal
% Add noise to the received signal in Rician channel
noise_real_rician = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for real part
noise_imag_rician = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for imaginary part
received_signal = fi((received_signal + noise_real_rician + fi(1i,1,16,10) * noise_imag_rician),1,49,20); % Add noise
else
error(‘hdl_compatible_code:UnknownChannelType’, ‘Unknown channel type’);
end
% QPSK demodulation
% Hard decision demodulation
% Decision regions
decision_regions = [fi(-1-1i,1,16,10), fi(-1+1i,1,16,10), fi(1-1i,1,16,10), fi(1+1i,1,16,10)];
% Initialize demodulated symbols
demodulated_symbols = zeros(1, n,’uint8′);
for i = 1:n
%Seperate real and imaginary part of received_signal and
%decision_regions
received_real = real(received_signal(i));
received_imag = imag(received_signal(i));
decision_real = real(decision_regions);
decision_imag = imag(decision_regions);
%Compute the absolute difference for real and imaginary parts
%seperately
diff_real = received_real – decision_real;
diff_imag = received_imag – decision_imag;
%Compute the absolute value using Pythagorean theorem
abs_diff = sqrt(diff_real.^2+diff_imag.^2);
%Find the index corresponding to the minimum absoloute difference
[~,~]=min(abs_diff);
end
% Calculate the error rate
errors = sum(bitxor(fi((data),0,8,0), fi((demodulated_symbols),0,8,0))); % Count errors
% Extract real and imaginary parts
received_signal_real = real(received_signal);
received_signal_imag = imag(received_signal);
error_rate = errors / n; % Calculate error rate
end
function noise = lfsr_noise(n)
% Linear feedback shift register (LFSR) for pseudo-random number generation
% Initialize LFSR state
lfsr_state = uint32(1);
noise = zeros(1, n,’like’,fi(0,1,16,10));
for i = 1:n
% Generate pseudo-random bit using xor feedback
new_bit = bitxor(bitget(lfsr_state, 1), bitget(lfsr_state, 3));
lfsr_state = bitshift(lfsr_state, -1);
lfsr_state = bitset(lfsr_state, 32, new_bit);
noise(i) = fi(lfsr_state,0,32,0) / fi(intmax(‘uint32’),1,16,10); % Scale [0,1]
end
end
function data = lfsr_data(n)
% Linear feedback shift register (LFSR) for generating random data
% Initialize LFSR state
lfsr_state = uint32(1);
data = zeros(1, n, ‘uint8’);
for i = 1:n
% Generate pseudo-random bit using xor feedback
new_bit = bitxor(bitget(lfsr_state, 1), bitget(lfsr_state, 3));
lfsr_state = bitshift(lfsr_state, -1);
lfsr_state = bitset(lfsr_state, 32, new_bit);
data(i) = fi((mod(lfsr_state,4)),0,2,0); % Generate random values in the range [0, 3]
end
end
function cos_value = cos_lookup(angle)
% Precompute cosine values for a range of angles
angles =fi( (0:0.01:2*pi),1,32,10); % Define the range of angles (adjust the step size as needed)
cos_values = fi((cos(angles)),1,16,10); % Compute cosine values
% Interpolate the cosine value for the given angle
cos_value = fi((zeros(size(angle))),1,16,10);
for i = 1:numel(angle)
[~,idx]=min(abs(angles-angle(i)));
cos_value(i)=cos_values(idx);
end
end
function y = log2_approx(x)
%Fixed-point logarithm base 2 approximation
y = fi(0,1,32,10);%Initialize y as fixed-point format
one = fi(1,1,32,10);%Define one in the same fixed-point format
sqrt2 = fi((sqrt(2)),1,32,10);%Define sqrt(2) in the same fixed -point format
for i = 1:32 %Limiting the iterations to 32 to avoid infinite loop
if x > one
x = bitsra(x,1);
y = fi((y + one),1,32,10);
end
end
frac = fi (0.5,1,32,10);
for i = 1:32
if x < one
x = bitsll(x,1);
y =fi( (y – one),1,32,10);
end
end
frac = fi (0.5,1,32,10);
two_pow_neg32 = fi((2^-32),1,32,10);
for i = 1:32
if x >= sqrt2
x = divide(x,sqrt2);
y =fi((y + frac) , 1,32,10);
end
frac = divide(frac,2);
end
end
function y = log10_approx(x)
%Approximate log10 function using a fixed-point approach
y = log2_approx(x)/ log2_approx(fi(10,1,32,10));
end
function result = divide(a,b)
%custom fixed-point division function
result = a/b;
result = fi(result,a.Signed,a.WordLength,a.FractionLength);
endthis is my code : MATLAB FUNCTION
function [received_signal_real, received_signal_imag, error_rate] = hdl_compatible_code(n, channel_type)
% Constants
aircraft_altitude = fi(45000,1,32,10); % Altitude of the aircraft in feet
distance_km = fi(350,1,32,10); % Distance between aircraft and base station in kilometers
speed_of_light = fi(3e8,1,32,10); % Speed of light in m/s
n = 100;
% Pathloss model – Free Space Path Loss (FSPL)
fc = fi(1.5e9,1,32,10); % Carrier frequency in Hz (1.5GHz)
lambda = speed_of_light / fc; % Wavelength
path_loss_dB = 20 *log10_approx(fi(4 * pi * distance_km * 1e3 / lambda,1,32,10)); % Path loss in dB
% AWGN
SNR_dB_awgn = fi(10,1,32,10); % Signal to noise ratio in dB for AWGN channel
SNR_awgn = fi(fi(10)^(SNR_dB_awgn / 10),1,32,10); % Convert SNR to linear scale for AWGN channel
tx_power_awgn = fi(1,1,32,10); % Initial guess for transmit power for AWGN channel
noise_power_awgn = tx_power_awgn / SNR_awgn; % Noise power based on SNR for AWGN channel
% Doppler spread
aircraft_speed = fi(660,1,32,10); % Average aircraft speed in meters per second
fd_max = fi(((aircraft_speed * fi(0.51444,1,32,10) * fc) / speed_of_light),1,32,10); % Doppler frequency shift
% Modulation using lookup table
% Precompute constellation points (Scalar approach)
constellation_points = [fi(1,1,16,10), fi(1i,1,16,10),fi(-1,1,16,10), fi(-1i,1,16,10)];
% Modulation
data = lfsr_data(n); % Generate random bits
qpsk_symbols = constellation_points(data + 1); % QPSK modulation: symbol mapping to complex constellation points
% Generate doppler effect using lookup table
two_pi_fd_max = fi(2*pi*fd_max,1,128,10);
t = fi((0:n-1) /n,1,32,10); % Time vector
doppler_shift = cos_lookup(fi((2 * pi * fd_max * t),1,32,10));
% Channel simulation
if channel_type == 0 % AWGN channel
noise_real = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for real part
noise_imag = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for imaginary part
received_signal = (qpsk_symbols .* doppler_shift) + noise_real + fi(1i,1,16,10) * noise_imag; % Received signal in AWGN channel
elseif channel_type == 1 % Rician fading channel
% Rician channel parameters
K =fi( 5,1,32,10); % Rician factor
LOS_power_dB =fi( -10,1,32,10); % Line of sight power in dB
LOS_power_linear = pow2(fi(10,1,32,10),LOS_power_dB/10); % Convert LOS power to linear scale
K_linear = pow2(fi(10,1,32,10),K/10); % Convert Rician factor to linear scale
% Generate fading coefficients
LOS = sqrt(LOS_power_linear / (2 * (1 + 1 / K_linear))) * ones(1, n,’like’,fi(0,1,16,10)); % LOS component
scattering = sqrt(LOS_power_linear / (2 * (1 + K_linear))) * (lfsr_noise(n) +fi( 1i,1,16,10) * lfsr_noise(n)); % Scattering component
fading_coefficient = LOS + scattering; % Rician fading coefficients
received_signal = (qpsk_symbols .* fading_coefficient .* doppler_shift); % Apply fading to the transmitted signal
% Add noise to the received signal in Rician channel
noise_real_rician = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for real part
noise_imag_rician = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for imaginary part
received_signal = fi((received_signal + noise_real_rician + fi(1i,1,16,10) * noise_imag_rician),1,49,20); % Add noise
else
error(‘hdl_compatible_code:UnknownChannelType’, ‘Unknown channel type’);
end
% QPSK demodulation
% Hard decision demodulation
% Decision regions
decision_regions = [fi(-1-1i,1,16,10), fi(-1+1i,1,16,10), fi(1-1i,1,16,10), fi(1+1i,1,16,10)];
% Initialize demodulated symbols
demodulated_symbols = zeros(1, n,’uint8′);
for i = 1:n
%Seperate real and imaginary part of received_signal and
%decision_regions
received_real = real(received_signal(i));
received_imag = imag(received_signal(i));
decision_real = real(decision_regions);
decision_imag = imag(decision_regions);
%Compute the absolute difference for real and imaginary parts
%seperately
diff_real = received_real – decision_real;
diff_imag = received_imag – decision_imag;
%Compute the absolute value using Pythagorean theorem
abs_diff = sqrt(diff_real.^2+diff_imag.^2);
%Find the index corresponding to the minimum absoloute difference
[~,~]=min(abs_diff);
end
% Calculate the error rate
errors = sum(bitxor(fi((data),0,8,0), fi((demodulated_symbols),0,8,0))); % Count errors
% Extract real and imaginary parts
received_signal_real = real(received_signal);
received_signal_imag = imag(received_signal);
error_rate = errors / n; % Calculate error rate
end
function noise = lfsr_noise(n)
% Linear feedback shift register (LFSR) for pseudo-random number generation
% Initialize LFSR state
lfsr_state = uint32(1);
noise = zeros(1, n,’like’,fi(0,1,16,10));
for i = 1:n
% Generate pseudo-random bit using xor feedback
new_bit = bitxor(bitget(lfsr_state, 1), bitget(lfsr_state, 3));
lfsr_state = bitshift(lfsr_state, -1);
lfsr_state = bitset(lfsr_state, 32, new_bit);
noise(i) = fi(lfsr_state,0,32,0) / fi(intmax(‘uint32’),1,16,10); % Scale [0,1]
end
end
function data = lfsr_data(n)
% Linear feedback shift register (LFSR) for generating random data
% Initialize LFSR state
lfsr_state = uint32(1);
data = zeros(1, n, ‘uint8’);
for i = 1:n
% Generate pseudo-random bit using xor feedback
new_bit = bitxor(bitget(lfsr_state, 1), bitget(lfsr_state, 3));
lfsr_state = bitshift(lfsr_state, -1);
lfsr_state = bitset(lfsr_state, 32, new_bit);
data(i) = fi((mod(lfsr_state,4)),0,2,0); % Generate random values in the range [0, 3]
end
end
function cos_value = cos_lookup(angle)
% Precompute cosine values for a range of angles
angles =fi( (0:0.01:2*pi),1,32,10); % Define the range of angles (adjust the step size as needed)
cos_values = fi((cos(angles)),1,16,10); % Compute cosine values
% Interpolate the cosine value for the given angle
cos_value = fi((zeros(size(angle))),1,16,10);
for i = 1:numel(angle)
[~,idx]=min(abs(angles-angle(i)));
cos_value(i)=cos_values(idx);
end
end
function y = log2_approx(x)
%Fixed-point logarithm base 2 approximation
y = fi(0,1,32,10);%Initialize y as fixed-point format
one = fi(1,1,32,10);%Define one in the same fixed-point format
sqrt2 = fi((sqrt(2)),1,32,10);%Define sqrt(2) in the same fixed -point format
for i = 1:32 %Limiting the iterations to 32 to avoid infinite loop
if x > one
x = bitsra(x,1);
y = fi((y + one),1,32,10);
end
end
frac = fi (0.5,1,32,10);
for i = 1:32
if x < one
x = bitsll(x,1);
y =fi( (y – one),1,32,10);
end
end
frac = fi (0.5,1,32,10);
two_pow_neg32 = fi((2^-32),1,32,10);
for i = 1:32
if x >= sqrt2
x = divide(x,sqrt2);
y =fi((y + frac) , 1,32,10);
end
frac = divide(frac,2);
end
end
function y = log10_approx(x)
%Approximate log10 function using a fixed-point approach
y = log2_approx(x)/ log2_approx(fi(10,1,32,10));
end
function result = divide(a,b)
%custom fixed-point division function
result = a/b;
result = fi(result,a.Signed,a.WordLength,a.FractionLength);
end this is my code : MATLAB FUNCTION
function [received_signal_real, received_signal_imag, error_rate] = hdl_compatible_code(n, channel_type)
% Constants
aircraft_altitude = fi(45000,1,32,10); % Altitude of the aircraft in feet
distance_km = fi(350,1,32,10); % Distance between aircraft and base station in kilometers
speed_of_light = fi(3e8,1,32,10); % Speed of light in m/s
n = 100;
% Pathloss model – Free Space Path Loss (FSPL)
fc = fi(1.5e9,1,32,10); % Carrier frequency in Hz (1.5GHz)
lambda = speed_of_light / fc; % Wavelength
path_loss_dB = 20 *log10_approx(fi(4 * pi * distance_km * 1e3 / lambda,1,32,10)); % Path loss in dB
% AWGN
SNR_dB_awgn = fi(10,1,32,10); % Signal to noise ratio in dB for AWGN channel
SNR_awgn = fi(fi(10)^(SNR_dB_awgn / 10),1,32,10); % Convert SNR to linear scale for AWGN channel
tx_power_awgn = fi(1,1,32,10); % Initial guess for transmit power for AWGN channel
noise_power_awgn = tx_power_awgn / SNR_awgn; % Noise power based on SNR for AWGN channel
% Doppler spread
aircraft_speed = fi(660,1,32,10); % Average aircraft speed in meters per second
fd_max = fi(((aircraft_speed * fi(0.51444,1,32,10) * fc) / speed_of_light),1,32,10); % Doppler frequency shift
% Modulation using lookup table
% Precompute constellation points (Scalar approach)
constellation_points = [fi(1,1,16,10), fi(1i,1,16,10),fi(-1,1,16,10), fi(-1i,1,16,10)];
% Modulation
data = lfsr_data(n); % Generate random bits
qpsk_symbols = constellation_points(data + 1); % QPSK modulation: symbol mapping to complex constellation points
% Generate doppler effect using lookup table
two_pi_fd_max = fi(2*pi*fd_max,1,128,10);
t = fi((0:n-1) /n,1,32,10); % Time vector
doppler_shift = cos_lookup(fi((2 * pi * fd_max * t),1,32,10));
% Channel simulation
if channel_type == 0 % AWGN channel
noise_real = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for real part
noise_imag = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for imaginary part
received_signal = (qpsk_symbols .* doppler_shift) + noise_real + fi(1i,1,16,10) * noise_imag; % Received signal in AWGN channel
elseif channel_type == 1 % Rician fading channel
% Rician channel parameters
K =fi( 5,1,32,10); % Rician factor
LOS_power_dB =fi( -10,1,32,10); % Line of sight power in dB
LOS_power_linear = pow2(fi(10,1,32,10),LOS_power_dB/10); % Convert LOS power to linear scale
K_linear = pow2(fi(10,1,32,10),K/10); % Convert Rician factor to linear scale
% Generate fading coefficients
LOS = sqrt(LOS_power_linear / (2 * (1 + 1 / K_linear))) * ones(1, n,’like’,fi(0,1,16,10)); % LOS component
scattering = sqrt(LOS_power_linear / (2 * (1 + K_linear))) * (lfsr_noise(n) +fi( 1i,1,16,10) * lfsr_noise(n)); % Scattering component
fading_coefficient = LOS + scattering; % Rician fading coefficients
received_signal = (qpsk_symbols .* fading_coefficient .* doppler_shift); % Apply fading to the transmitted signal
% Add noise to the received signal in Rician channel
noise_real_rician = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for real part
noise_imag_rician = sqrt(noise_power_awgn / 2) * lfsr_noise(n); % Generate noise for imaginary part
received_signal = fi((received_signal + noise_real_rician + fi(1i,1,16,10) * noise_imag_rician),1,49,20); % Add noise
else
error(‘hdl_compatible_code:UnknownChannelType’, ‘Unknown channel type’);
end
% QPSK demodulation
% Hard decision demodulation
% Decision regions
decision_regions = [fi(-1-1i,1,16,10), fi(-1+1i,1,16,10), fi(1-1i,1,16,10), fi(1+1i,1,16,10)];
% Initialize demodulated symbols
demodulated_symbols = zeros(1, n,’uint8′);
for i = 1:n
%Seperate real and imaginary part of received_signal and
%decision_regions
received_real = real(received_signal(i));
received_imag = imag(received_signal(i));
decision_real = real(decision_regions);
decision_imag = imag(decision_regions);
%Compute the absolute difference for real and imaginary parts
%seperately
diff_real = received_real – decision_real;
diff_imag = received_imag – decision_imag;
%Compute the absolute value using Pythagorean theorem
abs_diff = sqrt(diff_real.^2+diff_imag.^2);
%Find the index corresponding to the minimum absoloute difference
[~,~]=min(abs_diff);
end
% Calculate the error rate
errors = sum(bitxor(fi((data),0,8,0), fi((demodulated_symbols),0,8,0))); % Count errors
% Extract real and imaginary parts
received_signal_real = real(received_signal);
received_signal_imag = imag(received_signal);
error_rate = errors / n; % Calculate error rate
end
function noise = lfsr_noise(n)
% Linear feedback shift register (LFSR) for pseudo-random number generation
% Initialize LFSR state
lfsr_state = uint32(1);
noise = zeros(1, n,’like’,fi(0,1,16,10));
for i = 1:n
% Generate pseudo-random bit using xor feedback
new_bit = bitxor(bitget(lfsr_state, 1), bitget(lfsr_state, 3));
lfsr_state = bitshift(lfsr_state, -1);
lfsr_state = bitset(lfsr_state, 32, new_bit);
noise(i) = fi(lfsr_state,0,32,0) / fi(intmax(‘uint32’),1,16,10); % Scale [0,1]
end
end
function data = lfsr_data(n)
% Linear feedback shift register (LFSR) for generating random data
% Initialize LFSR state
lfsr_state = uint32(1);
data = zeros(1, n, ‘uint8’);
for i = 1:n
% Generate pseudo-random bit using xor feedback
new_bit = bitxor(bitget(lfsr_state, 1), bitget(lfsr_state, 3));
lfsr_state = bitshift(lfsr_state, -1);
lfsr_state = bitset(lfsr_state, 32, new_bit);
data(i) = fi((mod(lfsr_state,4)),0,2,0); % Generate random values in the range [0, 3]
end
end
function cos_value = cos_lookup(angle)
% Precompute cosine values for a range of angles
angles =fi( (0:0.01:2*pi),1,32,10); % Define the range of angles (adjust the step size as needed)
cos_values = fi((cos(angles)),1,16,10); % Compute cosine values
% Interpolate the cosine value for the given angle
cos_value = fi((zeros(size(angle))),1,16,10);
for i = 1:numel(angle)
[~,idx]=min(abs(angles-angle(i)));
cos_value(i)=cos_values(idx);
end
end
function y = log2_approx(x)
%Fixed-point logarithm base 2 approximation
y = fi(0,1,32,10);%Initialize y as fixed-point format
one = fi(1,1,32,10);%Define one in the same fixed-point format
sqrt2 = fi((sqrt(2)),1,32,10);%Define sqrt(2) in the same fixed -point format
for i = 1:32 %Limiting the iterations to 32 to avoid infinite loop
if x > one
x = bitsra(x,1);
y = fi((y + one),1,32,10);
end
end
frac = fi (0.5,1,32,10);
for i = 1:32
if x < one
x = bitsll(x,1);
y =fi( (y – one),1,32,10);
end
end
frac = fi (0.5,1,32,10);
two_pow_neg32 = fi((2^-32),1,32,10);
for i = 1:32
if x >= sqrt2
x = divide(x,sqrt2);
y =fi((y + frac) , 1,32,10);
end
frac = divide(frac,2);
end
end
function y = log10_approx(x)
%Approximate log10 function using a fixed-point approach
y = log2_approx(x)/ log2_approx(fi(10,1,32,10));
end
function result = divide(a,b)
%custom fixed-point division function
result = a/b;
result = fi(result,a.Signed,a.WordLength,a.FractionLength);
end hdl coder compatible code MATLAB Answers — New Questions
Requirements manager: How to maintain bidirectional requirements
Hi all.
After that I’ve created the requirements structure in exel file and i imported the requirements from the exel file into the Requirements manager, if I modify the requirements in the Requirements manager there is the possibility to maintain the bidirectionality of the change automatically with some mechanism or with an export function in the source exel file.
Thank you in advance.Hi all.
After that I’ve created the requirements structure in exel file and i imported the requirements from the exel file into the Requirements manager, if I modify the requirements in the Requirements manager there is the possibility to maintain the bidirectionality of the change automatically with some mechanism or with an export function in the source exel file.
Thank you in advance. Hi all.
After that I’ve created the requirements structure in exel file and i imported the requirements from the exel file into the Requirements manager, if I modify the requirements in the Requirements manager there is the possibility to maintain the bidirectionality of the change automatically with some mechanism or with an export function in the source exel file.
Thank you in advance. requirements manager MATLAB Answers — New Questions
(help) How to add your own Power Automate flows in “apps” in group chat
Hi,
I have created multiple power automate flows with various purposes that are active in this group chat on TEAMS, but I would like to know if there is a way to add my custom flows here in this “apps” window to run them from there, or edit the default list.
I would also like to know if there is a way to anchor the workflows icon here, something like this:
Hi,I have created multiple power automate flows with various purposes that are active in this group chat on TEAMS, but I would like to know if there is a way to add my custom flows here in this “apps” window to run them from there, or edit the default list. I would also like to know if there is a way to anchor the workflows icon here, something like this: Read More
Per-User MFA State Added to Tenant Passwords and MFA Report
A Microsoft Graph update makes per-user MFA state available for user accounts. Being able to access the data means that we can include it in the User Passwords and Authentication report. You can now see if accounts are disabled, enabled, or enforced for per-user MFA along with all the other information captured about passwqrd changes, MFA authentication methods, and so on.
https://office365itpros.com/2024/06/14/per-user-mfa-state/
A Microsoft Graph update makes per-user MFA state available for user accounts. Being able to access the data means that we can include it in the User Passwords and Authentication report. You can now see if accounts are disabled, enabled, or enforced for per-user MFA along with all the other information captured about passwqrd changes, MFA authentication methods, and so on.
https://office365itpros.com/2024/06/14/per-user-mfa-state/ Read More
Free Trials & Private Offers
Hello!
I am unsure if this is the right place to ask this, so feel free to direct me elsewhere if not!
We offer Customers the ability to trial our solution directly with us for free for 14 days before purchasing, when starting our Marketplace journey we wanted to keep our listing aligned with what we offer directly to Customers on our Website. When initially listing on the Marketplace, we created a ‘free trial’ through the ‘Get It Now’ button, but what we quickly came to realise is that the free trial is also extended for Private Offers too if you have it activated on your listing.
This has caused issues because we do have Customers who are ready to buy now, buying through Private Offer and were being given the months free trial as well, essentially giving them the option to cancel in that months window, however if we were to have transacted directly with the Customer they would have been a paying Customer as soon as they had signed with us.
We have now turned off our free trial on our Marketplace listing because of this, but I have noticed a decline in activity on our listing as a result of this.
I just wanted to reach out and see if there were any other ISV’s facing a similar problem and if anyone knew if there was a way to get around it and essentially turn off the free trial for Private Offers? If there isn’t today, is anyone aware of any developments in the near future to rectify this?
Hello! I am unsure if this is the right place to ask this, so feel free to direct me elsewhere if not! We offer Customers the ability to trial our solution directly with us for free for 14 days before purchasing, when starting our Marketplace journey we wanted to keep our listing aligned with what we offer directly to Customers on our Website. When initially listing on the Marketplace, we created a ‘free trial’ through the ‘Get It Now’ button, but what we quickly came to realise is that the free trial is also extended for Private Offers too if you have it activated on your listing. This has caused issues because we do have Customers who are ready to buy now, buying through Private Offer and were being given the months free trial as well, essentially giving them the option to cancel in that months window, however if we were to have transacted directly with the Customer they would have been a paying Customer as soon as they had signed with us. We have now turned off our free trial on our Marketplace listing because of this, but I have noticed a decline in activity on our listing as a result of this. I just wanted to reach out and see if there were any other ISV’s facing a similar problem and if anyone knew if there was a way to get around it and essentially turn off the free trial for Private Offers? If there isn’t today, is anyone aware of any developments in the near future to rectify this? Read More
Meet Microsoft at FinOpsX 2024 in San Diego
For the second time, Microsoft will be a platinum sponsor of the FinOps X conference, taking place in
San Diego, CA, from June 19 – 22. This year, you can visit our dedicated Microsoft Event Hub website to learn more about our activities, connect with our experts, and register for our exclusive sessions.
This includes:
Our exclusive evening event, where you can network with industry leaders over amazing food, and celebrate the kickoff of FinOpsX. Spaces are limited.
Customer insight sessions with in-depth discussions and feedback. Register for one of the 45min time slots.
Microsoft speakers in the following sessions:
Unveiling Chevron’s transformation
Navigating new intersections and trends
Bring your data into the AI era – democratize FinOps with Microsoft
Profiles of Microsoft experts who will be attending, so you can connect with them on LinkedIn.
Learn more and register now for Microsoft sessions: https://finops.event-rsvp.net/
For event details and attendee registration, visit https://x.finops.org/us/
Microsoft Tech Community – Latest Blogs –Read More
Hi, I want to plot the eigenvalue of the Orr-Sommerfeld operator at different instants in time. How can I do that?
% p40.m – eigenvalues of Orr-Sommerfeld operator (compare p38.m)
R = 5772; clf, [ay,ax] = meshgrid([.56 .04],[.1 .5]);
for N = 40:20:100
% 2nd- and 4th-order differentiation matrices:
[D,x] = cheb(N); D2 = D^2; D2 = D2(2:N,2:N);
S = diag([0; 1 ./(1-x(2:N).^2); 0]);
D4 = (diag(1-x.^2)*D^4 – 8*diag(x)*D^3 – 12*D^2)*S;
D4 = D4(2:N,2:N);
% Orr-Sommerfeld operators A,B and generalized eigenvalues:
I = eye(N-1);
A = (D4-2*D2+I)/R – 2i*I – 1i*diag(1-x(2:N).^2)*(D2-I);
B = D2-I;
ee = eig(A,B);
i = N/20-1; subplot(‘position’,[ax(i) ay(i) .38 .38])
plot(ee,’.’,’markersize’,12)
grid on, axis([-.8 .2 -1 0]), axis square
title([‘N = ‘ int2str(N) ‘ lambda_{max} = ‘ …
num2str(max(real(ee)),’%16.12f’)]), drawnow
end
with the help of eigenshuffle function.
function [Vseq,Dseq] = eigenshuffle(Asequence,Bsequence)
% eigenshuffle: Consistent sorting for an eigenvalue/vector sequence
% [Vseq,Dseq] = eigenshuffle(Asequence)
% [Vseq,Dseq] = eigenshuffle(Asequence,Bsequence)
%
% Includes munkres.m (by gracious permission from Yi Cao)
% to choose the appropriate permutation. This greatly
% enhances the speed of eigenshuffle over my previous
% release.
%
% http://www.mathworks.com/matlabcentral/fileexchange/20652
%
% Arguments: (input)
% Asequence – an array of eigenvalue problems. If
% Asequence is a 3-d numeric array, then each
% plane of Asequence must contain a square
% matrix that will be used to call eig.
%
% Eig will be called on each of these matrices
% to produce a series of eigenvalues/vectors,
% one such set for each eigenvalue problem.
%
% Bsequence – (OPTIONAL) This allows the user to solve
% generalized eigenvalue problems of the form
%
% A*X = lambda*B*x
%
% Bsequence must be the same shape and size as
% Asequence.
%
% ONLY supply Bsequence when generalized eigenvalues
% will be computed.
%
% Arguments: (Output)
% Vseq – a 3-d array (pxpxn) of eigenvectors. Each
% plane of the array will be sorted into a
% consistent order with the other eigenvalue
% problems. The ordering chosen will be one
% that maximizes the energy of the consecutive
% eigensystems relative to each other.
%
% Dseq – pxn array of eigen values, sorted in order
% to be consistent with each other and with the
% eigenvectors in Vseq.
%
% Example:
% Efun = @(t) [1 2*t+1 t^2 t^3;2*t+1 2-t t^2 1-t^3; …
% t^2 t^2 3-2*t t^2;t^3 1-t^3 t^2 4-3*t];
%
% Aseq = zeros(4,4,21);
% for i = 1:21
% Aseq(:,:,i) = Efun((i-11)/10);
% end
% [Vseq,Dseq] = eigenshuffle(Aseq);
%
% To see that eigenshuffle has done its work correctly,
% look at the eigenvalues in sequence, after the shuffle.
%
% t = (-1:.1:1)’;
% [t,Dseq’]
% ans =
% -1 8.4535 5 2.3447 0.20181
% -0.9 7.8121 4.7687 2.3728 0.44644
% -0.8 7.2481 4.56 2.3413 0.65054
% -0.7 6.7524 4.3648 2.2709 0.8118
% -0.6 6.3156 4.1751 2.1857 0.92364
% -0.5 5.9283 3.9855 2.1118 0.97445
% -0.4 5.5816 3.7931 2.0727 0.95254
% -0.3 5.2676 3.5976 2.0768 0.858
% -0.2 4.9791 3.3995 2.1156 0.70581
% -0.1 4.7109 3.2 2.1742 0.51494
% 0 4.4605 3 2.2391 0.30037
% 0.1 4.2302 2.8 2.2971 0.072689
% 0.2 4.0303 2.5997 2.3303 -0.16034
% 0.3 3.8817 2.4047 2.3064 -0.39272
% 0.4 3.8108 2.1464 2.2628 -0.62001
% 0.5 3.8302 1.8986 2.1111 -0.83992
% 0.6 3.9301 1.5937 1.9298 -1.0537
% 0.7 4.0927 1.2308 1.745 -1.2685
% 0.8 4.3042 0.82515 1.5729 -1.5023
% 0.9 4.5572 0.40389 1.4272 -1.7883
% 1 4.8482 -8.0012e-16 1.3273 -2.1755
%
% Here, the columns are the shuffled eigenvalues.
% See that the second eigenvalue goes to zero, but
% the third eigenvalue remains positive. We can plot
% eigenvalues and see that they have crossed, near
% t = 0.35 in Efun.
%
% plot(-1:.1:1,Dseq’)
%
% For a better appreciation of what eigenshuffle did,
% compare the result of eig directly on Efun(.3) and
% Efun(.4). Thus:
%
% [V3,D3] = eig(Efun(.3))
% V3 =
% -0.74139 0.53464 -0.23551 0.3302
% 0.64781 0.4706 -0.16256 0.57659
% 0.0086542 -0.44236 -0.89119 0.10006
% -0.17496 -0.54498 0.35197 0.74061
%
% D3 =
% -0.39272 0 0 0
% 0 2.3064 0 0
% 0 0 2.4047 0
% 0 0 0 3.8817
%
% [V4,D4] = eig(Efun(.4))
% V4 =
% -0.73026 0.19752 0.49743 0.42459
% 0.66202 0.21373 0.35297 0.62567
% 0.013412 -0.95225 0.25513 0.16717
% -0.16815 -0.092308 -0.75026 0.63271
%
% D4 =
% -0.62001 0 0 0
% 0 2.1464 0 0
% 0 0 2.2628 0
% 0 0 0 3.8108
%
% With no sort or shuffle applied, look at V3(:,3). See
% that it is really closest to V4(:,2), but with a sign
% flip. Since the signs on the eigenvectors are arbitrary,
% the sign is changed, and the most consistent sequence
% will be chosen. By way of comparison, see how the
% eigenvectors in Vseq have been shuffled, the signs
% swapped appropriately.
%
% Vseq(:,:,14)
% ans =
% 0.3302 0.23551 -0.53464 0.74139
% 0.57659 0.16256 -0.4706 -0.64781
% 0.10006 0.89119 0.44236 -0.0086542
% 0.74061 -0.35197 0.54498 0.17496
%
% Vseq(:,:,15)
% ans =
% 0.42459 -0.19752 -0.49743 0.73026
% 0.62567 -0.21373 -0.35297 -0.66202
% 0.16717 0.95225 -0.25513 -0.013412
% 0.63271 0.092308 0.75026 0.16815
%
% See also: eig
%
% Author: John D’Errico
% e-mail: woodchips@rochester.rr.com
% Release: 3.0
% Release date: 2/18/09
% Is Asequence a 3-d array?
Asize = size(Asequence);
if (Asize(1)~=Asize(2))
error(‘Asequence must be a (pxpxn) array of eigen-problems, each of size pxp’)
end
% was Bsequence supplied
genflag = false;
if (nargin > 1) & ~isempty(Bsequence)
genflag = true;
if ~isequal(size(Asequence),size(Bsequence))
error(‘If Bsequence is provided to compute generalized eigenvalues, then Asequence and Bsequence must be the same size arrays’)
end
end
p = Asize(1);
if length(Asize)<3
n = 1;
else
n = Asize(3);
end
% the initial eigenvalues/vectors in nominal order
Vseq = zeros(p,p,n);
Dseq = zeros(p,n);
for i = 1:n
if genflag
[V,D] = eig(Asequence(:,:,i),Bsequence(:,:,i));
else
[V,D] = eig(Asequence(:,:,i));
end
D = diag(D);
% initial ordering is purely in decreasing order.
% If any are complex, the sort is in terms of the
% real part.
[junk,tags] = sort(real(D),1,’descend’);
Dseq(:,i) = D(tags);
Vseq(:,:,i) = V(:,tags);
end
% was there only one eigenvalue problem?
if n < 2
% we can quit now, having sorted the eigenvalues
% as best as we could.
return
end
% now, treat each eigenproblem in sequence (after
% the first one.)
for i = 2:n
% compute distance between systems
V1 = Vseq(:,:,i-1);
V2 = Vseq(:,:,i);
D1 = Dseq(:,i-1);
D2 = Dseq(:,i);
dist = (1-abs(V1’*V2)).*sqrt( …
distancematrix(real(D1),real(D2)).^2+ …
distancematrix(imag(D1),imag(D2)).^2);
% Is there a best permutation? use munkres.
% much faster than my own mintrace, munkres
% is used by gracious permission from Yi Cao.
reorder = munkres(dist);
Vseq(:,:,i) = Vseq(:,reorder,i);
Dseq(:,i) = Dseq(reorder,i);
% also ensure the signs of each eigenvector pair
% were consistent if possible
S = squeeze(real(sum(Vseq(:,:,i-1).*Vseq(:,:,i),1))) < 0;
Vseq(:,S,i) = -Vseq(:,S,i);
end
% =================
% end mainline
% =================
% begin subfunctions
% =================
function d = distancematrix(vec1,vec2)
% simple interpoint distance matrix
[vec1,vec2] = ndgrid(vec1,vec2);
d = abs(vec1 – vec2);
function [assignment,cost] = munkres(costMat)
% MUNKRES Munkres (Hungarian) Algorithm for Linear Assignment Problem.
%
% [ASSIGN,COST] = munkres(COSTMAT) returns the optimal column indices,
% ASSIGN assigned to each row and the minimum COST based on the assignment
% problem represented by the COSTMAT, where the (i,j)th element represents the cost to assign the jth
% job to the ith worker.
%
% This is vectorized implementation of the algorithm. It is the fastest
% among all Matlab implementations of the algorithm.
% Examples
% Example 1: a 5 x 5 example
%{
[assignment,cost] = munkres(magic(5));
disp(assignment); % 3 2 1 5 4
disp(cost); %15
%}
% Example 2: 400 x 400 random data
%{
n=400;
A=rand(n);
tic
[a,b]=munkres(A);
toc % about 2 seconds
%}
% Example 3: rectangular assignment with inf costs
%{
A=rand(10,7);
A(A>0.7)=Inf;
[a,b]=munkres(A);
%}
% Reference:
% "Munkres’ Assignment Algorithm, Modified for Rectangular Matrices",
% http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html
% version 2.0 by Yi Cao at Cranfield University on 10th July 2008
assignment = zeros(1,size(costMat,1));
cost = 0;
costMat(costMat~=costMat)=Inf;
validMat = costMat<Inf;
validCol = any(validMat,1);
validRow = any(validMat,2);
nRows = sum(validRow);
nCols = sum(validCol);
n = max(nRows,nCols);
if ~n
return
end
maxv=10*max(costMat(validMat));
dMat = zeros(n) + maxv;
dMat(1:nRows,1:nCols) = costMat(validRow,validCol);
%*************************************************
% Munkres’ Assignment Algorithm starts here
%*************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STEP 1: Subtract the row minimum from each row.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
minR = min(dMat,[],2);
minC = min(bsxfun(@minus, dMat, minR));
%**************************************************************************
% STEP 2: Find a zero of dMat. If there are no starred zeros in its
% column or row start the zero. Repeat for each zero
%**************************************************************************
zP = dMat == bsxfun(@plus, minC, minR);
starZ = zeros(n,1);
while any(zP(:))
[r,c]=find(zP,1);
starZ(r)=c;
zP(r,:)=false;
zP(:,c)=false;
end
while 1
%**************************************************************************
% STEP 3: Cover each column with a starred zero. If all the columns are
% covered then the matching is maximum
%**************************************************************************
if all(starZ>0)
break
end
coverColumn = false(1,n);
coverColumn(starZ(starZ>0))=true;
coverRow = false(n,1);
primeZ = zeros(n,1);
[rIdx, cIdx] = find(dMat(~coverRow,~coverColumn)==bsxfun(@plus,minR(~coverRow),minC(~coverColumn)));
while 1
%**************************************************************************
% STEP 4: Find a noncovered zero and prime it. If there is no starred
% zero in the row containing this primed zero, Go to Step 5.
% Otherwise, cover this row and uncover the column containing
% the starred zero. Continue in this manner until there are no
% uncovered zeros left. Save the smallest uncovered value and
% Go to Step 6.
%**************************************************************************
cR = find(~coverRow);
cC = find(~coverColumn);
rIdx = cR(rIdx);
cIdx = cC(cIdx);
Step = 6;
while ~isempty(cIdx)
uZr = rIdx(1);
uZc = cIdx(1);
primeZ(uZr) = uZc;
stz = starZ(uZr);
if ~stz
Step = 5;
break;
end
coverRow(uZr) = true;
coverColumn(stz) = false;
z = rIdx==uZr;
rIdx(z) = [];
cIdx(z) = [];
cR = find(~coverRow);
z = dMat(~coverRow,stz) == minR(~coverRow) + minC(stz);
rIdx = [rIdx(:);cR(z)];
cIdx = [cIdx(:);stz(ones(sum(z),1))];
end
if Step == 6
% *************************************************************************
% STEP 6: Add the minimum uncovered value to every element of each covered
% row, and subtract it from every element of each uncovered column.
% Return to Step 4 without altering any stars, primes, or covered lines.
%**************************************************************************
[minval,rIdx,cIdx]=outerplus(dMat(~coverRow,~coverColumn),minR(~coverRow),minC(~coverColumn));
minC(~coverColumn) = minC(~coverColumn) + minval;
minR(coverRow) = minR(coverRow) – minval;
else
break
end
end
%**************************************************************************
% STEP 5:
% Construct a series of alternating primed and starred zeros as
% follows:
% Let Z0 represent the uncovered primed zero found in Step 4.
% Let Z1 denote the starred zero in the column of Z0 (if any).
% Let Z2 denote the primed zero in the row of Z1 (there will always
% be one). Continue until the series terminates at a primed zero
% that has no starred zero in its column. Unstar each starred
% zero of the series, star each primed zero of the series, erase
% all primes and uncover every line in the matrix. Return to Step 3.
%**************************************************************************
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
while rowZ1>0
starZ(rowZ1)=0;
uZc = primeZ(rowZ1);
uZr = rowZ1;
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
end
end
% Cost of assignment
rowIdx = find(validRow);
colIdx = find(validCol);
starZ = starZ(1:nRows);
vIdx = starZ <= nCols;
assignment(rowIdx(vIdx)) = colIdx(starZ(vIdx));
cost = trace(costMat(assignment>0,assignment(assignment>0)));
function [minval,rIdx,cIdx]=outerplus(M,x,y)
[nx,ny]=size(M);
minval=inf;
for r=1:nx
x1=x(r);
for c=1:ny
M(r,c)=M(r,c)-(x1+y(c));
if minval>M(r,c)
minval=M(r,c);
end
end
end
[rIdx,cIdx]=find(M==minval);
This code is from SPECTRAL METHODS IN MATLAB by Trefethen. The eigenvalue problem is solved here. But for t>0, how can I calculate eigenvalues? . Dont hasitate to ask me any questien if my problem was mis understood. Thanks in advance.% p40.m – eigenvalues of Orr-Sommerfeld operator (compare p38.m)
R = 5772; clf, [ay,ax] = meshgrid([.56 .04],[.1 .5]);
for N = 40:20:100
% 2nd- and 4th-order differentiation matrices:
[D,x] = cheb(N); D2 = D^2; D2 = D2(2:N,2:N);
S = diag([0; 1 ./(1-x(2:N).^2); 0]);
D4 = (diag(1-x.^2)*D^4 – 8*diag(x)*D^3 – 12*D^2)*S;
D4 = D4(2:N,2:N);
% Orr-Sommerfeld operators A,B and generalized eigenvalues:
I = eye(N-1);
A = (D4-2*D2+I)/R – 2i*I – 1i*diag(1-x(2:N).^2)*(D2-I);
B = D2-I;
ee = eig(A,B);
i = N/20-1; subplot(‘position’,[ax(i) ay(i) .38 .38])
plot(ee,’.’,’markersize’,12)
grid on, axis([-.8 .2 -1 0]), axis square
title([‘N = ‘ int2str(N) ‘ lambda_{max} = ‘ …
num2str(max(real(ee)),’%16.12f’)]), drawnow
end
with the help of eigenshuffle function.
function [Vseq,Dseq] = eigenshuffle(Asequence,Bsequence)
% eigenshuffle: Consistent sorting for an eigenvalue/vector sequence
% [Vseq,Dseq] = eigenshuffle(Asequence)
% [Vseq,Dseq] = eigenshuffle(Asequence,Bsequence)
%
% Includes munkres.m (by gracious permission from Yi Cao)
% to choose the appropriate permutation. This greatly
% enhances the speed of eigenshuffle over my previous
% release.
%
% http://www.mathworks.com/matlabcentral/fileexchange/20652
%
% Arguments: (input)
% Asequence – an array of eigenvalue problems. If
% Asequence is a 3-d numeric array, then each
% plane of Asequence must contain a square
% matrix that will be used to call eig.
%
% Eig will be called on each of these matrices
% to produce a series of eigenvalues/vectors,
% one such set for each eigenvalue problem.
%
% Bsequence – (OPTIONAL) This allows the user to solve
% generalized eigenvalue problems of the form
%
% A*X = lambda*B*x
%
% Bsequence must be the same shape and size as
% Asequence.
%
% ONLY supply Bsequence when generalized eigenvalues
% will be computed.
%
% Arguments: (Output)
% Vseq – a 3-d array (pxpxn) of eigenvectors. Each
% plane of the array will be sorted into a
% consistent order with the other eigenvalue
% problems. The ordering chosen will be one
% that maximizes the energy of the consecutive
% eigensystems relative to each other.
%
% Dseq – pxn array of eigen values, sorted in order
% to be consistent with each other and with the
% eigenvectors in Vseq.
%
% Example:
% Efun = @(t) [1 2*t+1 t^2 t^3;2*t+1 2-t t^2 1-t^3; …
% t^2 t^2 3-2*t t^2;t^3 1-t^3 t^2 4-3*t];
%
% Aseq = zeros(4,4,21);
% for i = 1:21
% Aseq(:,:,i) = Efun((i-11)/10);
% end
% [Vseq,Dseq] = eigenshuffle(Aseq);
%
% To see that eigenshuffle has done its work correctly,
% look at the eigenvalues in sequence, after the shuffle.
%
% t = (-1:.1:1)’;
% [t,Dseq’]
% ans =
% -1 8.4535 5 2.3447 0.20181
% -0.9 7.8121 4.7687 2.3728 0.44644
% -0.8 7.2481 4.56 2.3413 0.65054
% -0.7 6.7524 4.3648 2.2709 0.8118
% -0.6 6.3156 4.1751 2.1857 0.92364
% -0.5 5.9283 3.9855 2.1118 0.97445
% -0.4 5.5816 3.7931 2.0727 0.95254
% -0.3 5.2676 3.5976 2.0768 0.858
% -0.2 4.9791 3.3995 2.1156 0.70581
% -0.1 4.7109 3.2 2.1742 0.51494
% 0 4.4605 3 2.2391 0.30037
% 0.1 4.2302 2.8 2.2971 0.072689
% 0.2 4.0303 2.5997 2.3303 -0.16034
% 0.3 3.8817 2.4047 2.3064 -0.39272
% 0.4 3.8108 2.1464 2.2628 -0.62001
% 0.5 3.8302 1.8986 2.1111 -0.83992
% 0.6 3.9301 1.5937 1.9298 -1.0537
% 0.7 4.0927 1.2308 1.745 -1.2685
% 0.8 4.3042 0.82515 1.5729 -1.5023
% 0.9 4.5572 0.40389 1.4272 -1.7883
% 1 4.8482 -8.0012e-16 1.3273 -2.1755
%
% Here, the columns are the shuffled eigenvalues.
% See that the second eigenvalue goes to zero, but
% the third eigenvalue remains positive. We can plot
% eigenvalues and see that they have crossed, near
% t = 0.35 in Efun.
%
% plot(-1:.1:1,Dseq’)
%
% For a better appreciation of what eigenshuffle did,
% compare the result of eig directly on Efun(.3) and
% Efun(.4). Thus:
%
% [V3,D3] = eig(Efun(.3))
% V3 =
% -0.74139 0.53464 -0.23551 0.3302
% 0.64781 0.4706 -0.16256 0.57659
% 0.0086542 -0.44236 -0.89119 0.10006
% -0.17496 -0.54498 0.35197 0.74061
%
% D3 =
% -0.39272 0 0 0
% 0 2.3064 0 0
% 0 0 2.4047 0
% 0 0 0 3.8817
%
% [V4,D4] = eig(Efun(.4))
% V4 =
% -0.73026 0.19752 0.49743 0.42459
% 0.66202 0.21373 0.35297 0.62567
% 0.013412 -0.95225 0.25513 0.16717
% -0.16815 -0.092308 -0.75026 0.63271
%
% D4 =
% -0.62001 0 0 0
% 0 2.1464 0 0
% 0 0 2.2628 0
% 0 0 0 3.8108
%
% With no sort or shuffle applied, look at V3(:,3). See
% that it is really closest to V4(:,2), but with a sign
% flip. Since the signs on the eigenvectors are arbitrary,
% the sign is changed, and the most consistent sequence
% will be chosen. By way of comparison, see how the
% eigenvectors in Vseq have been shuffled, the signs
% swapped appropriately.
%
% Vseq(:,:,14)
% ans =
% 0.3302 0.23551 -0.53464 0.74139
% 0.57659 0.16256 -0.4706 -0.64781
% 0.10006 0.89119 0.44236 -0.0086542
% 0.74061 -0.35197 0.54498 0.17496
%
% Vseq(:,:,15)
% ans =
% 0.42459 -0.19752 -0.49743 0.73026
% 0.62567 -0.21373 -0.35297 -0.66202
% 0.16717 0.95225 -0.25513 -0.013412
% 0.63271 0.092308 0.75026 0.16815
%
% See also: eig
%
% Author: John D’Errico
% e-mail: woodchips@rochester.rr.com
% Release: 3.0
% Release date: 2/18/09
% Is Asequence a 3-d array?
Asize = size(Asequence);
if (Asize(1)~=Asize(2))
error(‘Asequence must be a (pxpxn) array of eigen-problems, each of size pxp’)
end
% was Bsequence supplied
genflag = false;
if (nargin > 1) & ~isempty(Bsequence)
genflag = true;
if ~isequal(size(Asequence),size(Bsequence))
error(‘If Bsequence is provided to compute generalized eigenvalues, then Asequence and Bsequence must be the same size arrays’)
end
end
p = Asize(1);
if length(Asize)<3
n = 1;
else
n = Asize(3);
end
% the initial eigenvalues/vectors in nominal order
Vseq = zeros(p,p,n);
Dseq = zeros(p,n);
for i = 1:n
if genflag
[V,D] = eig(Asequence(:,:,i),Bsequence(:,:,i));
else
[V,D] = eig(Asequence(:,:,i));
end
D = diag(D);
% initial ordering is purely in decreasing order.
% If any are complex, the sort is in terms of the
% real part.
[junk,tags] = sort(real(D),1,’descend’);
Dseq(:,i) = D(tags);
Vseq(:,:,i) = V(:,tags);
end
% was there only one eigenvalue problem?
if n < 2
% we can quit now, having sorted the eigenvalues
% as best as we could.
return
end
% now, treat each eigenproblem in sequence (after
% the first one.)
for i = 2:n
% compute distance between systems
V1 = Vseq(:,:,i-1);
V2 = Vseq(:,:,i);
D1 = Dseq(:,i-1);
D2 = Dseq(:,i);
dist = (1-abs(V1’*V2)).*sqrt( …
distancematrix(real(D1),real(D2)).^2+ …
distancematrix(imag(D1),imag(D2)).^2);
% Is there a best permutation? use munkres.
% much faster than my own mintrace, munkres
% is used by gracious permission from Yi Cao.
reorder = munkres(dist);
Vseq(:,:,i) = Vseq(:,reorder,i);
Dseq(:,i) = Dseq(reorder,i);
% also ensure the signs of each eigenvector pair
% were consistent if possible
S = squeeze(real(sum(Vseq(:,:,i-1).*Vseq(:,:,i),1))) < 0;
Vseq(:,S,i) = -Vseq(:,S,i);
end
% =================
% end mainline
% =================
% begin subfunctions
% =================
function d = distancematrix(vec1,vec2)
% simple interpoint distance matrix
[vec1,vec2] = ndgrid(vec1,vec2);
d = abs(vec1 – vec2);
function [assignment,cost] = munkres(costMat)
% MUNKRES Munkres (Hungarian) Algorithm for Linear Assignment Problem.
%
% [ASSIGN,COST] = munkres(COSTMAT) returns the optimal column indices,
% ASSIGN assigned to each row and the minimum COST based on the assignment
% problem represented by the COSTMAT, where the (i,j)th element represents the cost to assign the jth
% job to the ith worker.
%
% This is vectorized implementation of the algorithm. It is the fastest
% among all Matlab implementations of the algorithm.
% Examples
% Example 1: a 5 x 5 example
%{
[assignment,cost] = munkres(magic(5));
disp(assignment); % 3 2 1 5 4
disp(cost); %15
%}
% Example 2: 400 x 400 random data
%{
n=400;
A=rand(n);
tic
[a,b]=munkres(A);
toc % about 2 seconds
%}
% Example 3: rectangular assignment with inf costs
%{
A=rand(10,7);
A(A>0.7)=Inf;
[a,b]=munkres(A);
%}
% Reference:
% "Munkres’ Assignment Algorithm, Modified for Rectangular Matrices",
% http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html
% version 2.0 by Yi Cao at Cranfield University on 10th July 2008
assignment = zeros(1,size(costMat,1));
cost = 0;
costMat(costMat~=costMat)=Inf;
validMat = costMat<Inf;
validCol = any(validMat,1);
validRow = any(validMat,2);
nRows = sum(validRow);
nCols = sum(validCol);
n = max(nRows,nCols);
if ~n
return
end
maxv=10*max(costMat(validMat));
dMat = zeros(n) + maxv;
dMat(1:nRows,1:nCols) = costMat(validRow,validCol);
%*************************************************
% Munkres’ Assignment Algorithm starts here
%*************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STEP 1: Subtract the row minimum from each row.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
minR = min(dMat,[],2);
minC = min(bsxfun(@minus, dMat, minR));
%**************************************************************************
% STEP 2: Find a zero of dMat. If there are no starred zeros in its
% column or row start the zero. Repeat for each zero
%**************************************************************************
zP = dMat == bsxfun(@plus, minC, minR);
starZ = zeros(n,1);
while any(zP(:))
[r,c]=find(zP,1);
starZ(r)=c;
zP(r,:)=false;
zP(:,c)=false;
end
while 1
%**************************************************************************
% STEP 3: Cover each column with a starred zero. If all the columns are
% covered then the matching is maximum
%**************************************************************************
if all(starZ>0)
break
end
coverColumn = false(1,n);
coverColumn(starZ(starZ>0))=true;
coverRow = false(n,1);
primeZ = zeros(n,1);
[rIdx, cIdx] = find(dMat(~coverRow,~coverColumn)==bsxfun(@plus,minR(~coverRow),minC(~coverColumn)));
while 1
%**************************************************************************
% STEP 4: Find a noncovered zero and prime it. If there is no starred
% zero in the row containing this primed zero, Go to Step 5.
% Otherwise, cover this row and uncover the column containing
% the starred zero. Continue in this manner until there are no
% uncovered zeros left. Save the smallest uncovered value and
% Go to Step 6.
%**************************************************************************
cR = find(~coverRow);
cC = find(~coverColumn);
rIdx = cR(rIdx);
cIdx = cC(cIdx);
Step = 6;
while ~isempty(cIdx)
uZr = rIdx(1);
uZc = cIdx(1);
primeZ(uZr) = uZc;
stz = starZ(uZr);
if ~stz
Step = 5;
break;
end
coverRow(uZr) = true;
coverColumn(stz) = false;
z = rIdx==uZr;
rIdx(z) = [];
cIdx(z) = [];
cR = find(~coverRow);
z = dMat(~coverRow,stz) == minR(~coverRow) + minC(stz);
rIdx = [rIdx(:);cR(z)];
cIdx = [cIdx(:);stz(ones(sum(z),1))];
end
if Step == 6
% *************************************************************************
% STEP 6: Add the minimum uncovered value to every element of each covered
% row, and subtract it from every element of each uncovered column.
% Return to Step 4 without altering any stars, primes, or covered lines.
%**************************************************************************
[minval,rIdx,cIdx]=outerplus(dMat(~coverRow,~coverColumn),minR(~coverRow),minC(~coverColumn));
minC(~coverColumn) = minC(~coverColumn) + minval;
minR(coverRow) = minR(coverRow) – minval;
else
break
end
end
%**************************************************************************
% STEP 5:
% Construct a series of alternating primed and starred zeros as
% follows:
% Let Z0 represent the uncovered primed zero found in Step 4.
% Let Z1 denote the starred zero in the column of Z0 (if any).
% Let Z2 denote the primed zero in the row of Z1 (there will always
% be one). Continue until the series terminates at a primed zero
% that has no starred zero in its column. Unstar each starred
% zero of the series, star each primed zero of the series, erase
% all primes and uncover every line in the matrix. Return to Step 3.
%**************************************************************************
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
while rowZ1>0
starZ(rowZ1)=0;
uZc = primeZ(rowZ1);
uZr = rowZ1;
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
end
end
% Cost of assignment
rowIdx = find(validRow);
colIdx = find(validCol);
starZ = starZ(1:nRows);
vIdx = starZ <= nCols;
assignment(rowIdx(vIdx)) = colIdx(starZ(vIdx));
cost = trace(costMat(assignment>0,assignment(assignment>0)));
function [minval,rIdx,cIdx]=outerplus(M,x,y)
[nx,ny]=size(M);
minval=inf;
for r=1:nx
x1=x(r);
for c=1:ny
M(r,c)=M(r,c)-(x1+y(c));
if minval>M(r,c)
minval=M(r,c);
end
end
end
[rIdx,cIdx]=find(M==minval);
This code is from SPECTRAL METHODS IN MATLAB by Trefethen. The eigenvalue problem is solved here. But for t>0, how can I calculate eigenvalues? . Dont hasitate to ask me any questien if my problem was mis understood. Thanks in advance. % p40.m – eigenvalues of Orr-Sommerfeld operator (compare p38.m)
R = 5772; clf, [ay,ax] = meshgrid([.56 .04],[.1 .5]);
for N = 40:20:100
% 2nd- and 4th-order differentiation matrices:
[D,x] = cheb(N); D2 = D^2; D2 = D2(2:N,2:N);
S = diag([0; 1 ./(1-x(2:N).^2); 0]);
D4 = (diag(1-x.^2)*D^4 – 8*diag(x)*D^3 – 12*D^2)*S;
D4 = D4(2:N,2:N);
% Orr-Sommerfeld operators A,B and generalized eigenvalues:
I = eye(N-1);
A = (D4-2*D2+I)/R – 2i*I – 1i*diag(1-x(2:N).^2)*(D2-I);
B = D2-I;
ee = eig(A,B);
i = N/20-1; subplot(‘position’,[ax(i) ay(i) .38 .38])
plot(ee,’.’,’markersize’,12)
grid on, axis([-.8 .2 -1 0]), axis square
title([‘N = ‘ int2str(N) ‘ lambda_{max} = ‘ …
num2str(max(real(ee)),’%16.12f’)]), drawnow
end
with the help of eigenshuffle function.
function [Vseq,Dseq] = eigenshuffle(Asequence,Bsequence)
% eigenshuffle: Consistent sorting for an eigenvalue/vector sequence
% [Vseq,Dseq] = eigenshuffle(Asequence)
% [Vseq,Dseq] = eigenshuffle(Asequence,Bsequence)
%
% Includes munkres.m (by gracious permission from Yi Cao)
% to choose the appropriate permutation. This greatly
% enhances the speed of eigenshuffle over my previous
% release.
%
% http://www.mathworks.com/matlabcentral/fileexchange/20652
%
% Arguments: (input)
% Asequence – an array of eigenvalue problems. If
% Asequence is a 3-d numeric array, then each
% plane of Asequence must contain a square
% matrix that will be used to call eig.
%
% Eig will be called on each of these matrices
% to produce a series of eigenvalues/vectors,
% one such set for each eigenvalue problem.
%
% Bsequence – (OPTIONAL) This allows the user to solve
% generalized eigenvalue problems of the form
%
% A*X = lambda*B*x
%
% Bsequence must be the same shape and size as
% Asequence.
%
% ONLY supply Bsequence when generalized eigenvalues
% will be computed.
%
% Arguments: (Output)
% Vseq – a 3-d array (pxpxn) of eigenvectors. Each
% plane of the array will be sorted into a
% consistent order with the other eigenvalue
% problems. The ordering chosen will be one
% that maximizes the energy of the consecutive
% eigensystems relative to each other.
%
% Dseq – pxn array of eigen values, sorted in order
% to be consistent with each other and with the
% eigenvectors in Vseq.
%
% Example:
% Efun = @(t) [1 2*t+1 t^2 t^3;2*t+1 2-t t^2 1-t^3; …
% t^2 t^2 3-2*t t^2;t^3 1-t^3 t^2 4-3*t];
%
% Aseq = zeros(4,4,21);
% for i = 1:21
% Aseq(:,:,i) = Efun((i-11)/10);
% end
% [Vseq,Dseq] = eigenshuffle(Aseq);
%
% To see that eigenshuffle has done its work correctly,
% look at the eigenvalues in sequence, after the shuffle.
%
% t = (-1:.1:1)’;
% [t,Dseq’]
% ans =
% -1 8.4535 5 2.3447 0.20181
% -0.9 7.8121 4.7687 2.3728 0.44644
% -0.8 7.2481 4.56 2.3413 0.65054
% -0.7 6.7524 4.3648 2.2709 0.8118
% -0.6 6.3156 4.1751 2.1857 0.92364
% -0.5 5.9283 3.9855 2.1118 0.97445
% -0.4 5.5816 3.7931 2.0727 0.95254
% -0.3 5.2676 3.5976 2.0768 0.858
% -0.2 4.9791 3.3995 2.1156 0.70581
% -0.1 4.7109 3.2 2.1742 0.51494
% 0 4.4605 3 2.2391 0.30037
% 0.1 4.2302 2.8 2.2971 0.072689
% 0.2 4.0303 2.5997 2.3303 -0.16034
% 0.3 3.8817 2.4047 2.3064 -0.39272
% 0.4 3.8108 2.1464 2.2628 -0.62001
% 0.5 3.8302 1.8986 2.1111 -0.83992
% 0.6 3.9301 1.5937 1.9298 -1.0537
% 0.7 4.0927 1.2308 1.745 -1.2685
% 0.8 4.3042 0.82515 1.5729 -1.5023
% 0.9 4.5572 0.40389 1.4272 -1.7883
% 1 4.8482 -8.0012e-16 1.3273 -2.1755
%
% Here, the columns are the shuffled eigenvalues.
% See that the second eigenvalue goes to zero, but
% the third eigenvalue remains positive. We can plot
% eigenvalues and see that they have crossed, near
% t = 0.35 in Efun.
%
% plot(-1:.1:1,Dseq’)
%
% For a better appreciation of what eigenshuffle did,
% compare the result of eig directly on Efun(.3) and
% Efun(.4). Thus:
%
% [V3,D3] = eig(Efun(.3))
% V3 =
% -0.74139 0.53464 -0.23551 0.3302
% 0.64781 0.4706 -0.16256 0.57659
% 0.0086542 -0.44236 -0.89119 0.10006
% -0.17496 -0.54498 0.35197 0.74061
%
% D3 =
% -0.39272 0 0 0
% 0 2.3064 0 0
% 0 0 2.4047 0
% 0 0 0 3.8817
%
% [V4,D4] = eig(Efun(.4))
% V4 =
% -0.73026 0.19752 0.49743 0.42459
% 0.66202 0.21373 0.35297 0.62567
% 0.013412 -0.95225 0.25513 0.16717
% -0.16815 -0.092308 -0.75026 0.63271
%
% D4 =
% -0.62001 0 0 0
% 0 2.1464 0 0
% 0 0 2.2628 0
% 0 0 0 3.8108
%
% With no sort or shuffle applied, look at V3(:,3). See
% that it is really closest to V4(:,2), but with a sign
% flip. Since the signs on the eigenvectors are arbitrary,
% the sign is changed, and the most consistent sequence
% will be chosen. By way of comparison, see how the
% eigenvectors in Vseq have been shuffled, the signs
% swapped appropriately.
%
% Vseq(:,:,14)
% ans =
% 0.3302 0.23551 -0.53464 0.74139
% 0.57659 0.16256 -0.4706 -0.64781
% 0.10006 0.89119 0.44236 -0.0086542
% 0.74061 -0.35197 0.54498 0.17496
%
% Vseq(:,:,15)
% ans =
% 0.42459 -0.19752 -0.49743 0.73026
% 0.62567 -0.21373 -0.35297 -0.66202
% 0.16717 0.95225 -0.25513 -0.013412
% 0.63271 0.092308 0.75026 0.16815
%
% See also: eig
%
% Author: John D’Errico
% e-mail: woodchips@rochester.rr.com
% Release: 3.0
% Release date: 2/18/09
% Is Asequence a 3-d array?
Asize = size(Asequence);
if (Asize(1)~=Asize(2))
error(‘Asequence must be a (pxpxn) array of eigen-problems, each of size pxp’)
end
% was Bsequence supplied
genflag = false;
if (nargin > 1) & ~isempty(Bsequence)
genflag = true;
if ~isequal(size(Asequence),size(Bsequence))
error(‘If Bsequence is provided to compute generalized eigenvalues, then Asequence and Bsequence must be the same size arrays’)
end
end
p = Asize(1);
if length(Asize)<3
n = 1;
else
n = Asize(3);
end
% the initial eigenvalues/vectors in nominal order
Vseq = zeros(p,p,n);
Dseq = zeros(p,n);
for i = 1:n
if genflag
[V,D] = eig(Asequence(:,:,i),Bsequence(:,:,i));
else
[V,D] = eig(Asequence(:,:,i));
end
D = diag(D);
% initial ordering is purely in decreasing order.
% If any are complex, the sort is in terms of the
% real part.
[junk,tags] = sort(real(D),1,’descend’);
Dseq(:,i) = D(tags);
Vseq(:,:,i) = V(:,tags);
end
% was there only one eigenvalue problem?
if n < 2
% we can quit now, having sorted the eigenvalues
% as best as we could.
return
end
% now, treat each eigenproblem in sequence (after
% the first one.)
for i = 2:n
% compute distance between systems
V1 = Vseq(:,:,i-1);
V2 = Vseq(:,:,i);
D1 = Dseq(:,i-1);
D2 = Dseq(:,i);
dist = (1-abs(V1’*V2)).*sqrt( …
distancematrix(real(D1),real(D2)).^2+ …
distancematrix(imag(D1),imag(D2)).^2);
% Is there a best permutation? use munkres.
% much faster than my own mintrace, munkres
% is used by gracious permission from Yi Cao.
reorder = munkres(dist);
Vseq(:,:,i) = Vseq(:,reorder,i);
Dseq(:,i) = Dseq(reorder,i);
% also ensure the signs of each eigenvector pair
% were consistent if possible
S = squeeze(real(sum(Vseq(:,:,i-1).*Vseq(:,:,i),1))) < 0;
Vseq(:,S,i) = -Vseq(:,S,i);
end
% =================
% end mainline
% =================
% begin subfunctions
% =================
function d = distancematrix(vec1,vec2)
% simple interpoint distance matrix
[vec1,vec2] = ndgrid(vec1,vec2);
d = abs(vec1 – vec2);
function [assignment,cost] = munkres(costMat)
% MUNKRES Munkres (Hungarian) Algorithm for Linear Assignment Problem.
%
% [ASSIGN,COST] = munkres(COSTMAT) returns the optimal column indices,
% ASSIGN assigned to each row and the minimum COST based on the assignment
% problem represented by the COSTMAT, where the (i,j)th element represents the cost to assign the jth
% job to the ith worker.
%
% This is vectorized implementation of the algorithm. It is the fastest
% among all Matlab implementations of the algorithm.
% Examples
% Example 1: a 5 x 5 example
%{
[assignment,cost] = munkres(magic(5));
disp(assignment); % 3 2 1 5 4
disp(cost); %15
%}
% Example 2: 400 x 400 random data
%{
n=400;
A=rand(n);
tic
[a,b]=munkres(A);
toc % about 2 seconds
%}
% Example 3: rectangular assignment with inf costs
%{
A=rand(10,7);
A(A>0.7)=Inf;
[a,b]=munkres(A);
%}
% Reference:
% "Munkres’ Assignment Algorithm, Modified for Rectangular Matrices",
% http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html
% version 2.0 by Yi Cao at Cranfield University on 10th July 2008
assignment = zeros(1,size(costMat,1));
cost = 0;
costMat(costMat~=costMat)=Inf;
validMat = costMat<Inf;
validCol = any(validMat,1);
validRow = any(validMat,2);
nRows = sum(validRow);
nCols = sum(validCol);
n = max(nRows,nCols);
if ~n
return
end
maxv=10*max(costMat(validMat));
dMat = zeros(n) + maxv;
dMat(1:nRows,1:nCols) = costMat(validRow,validCol);
%*************************************************
% Munkres’ Assignment Algorithm starts here
%*************************************************
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% STEP 1: Subtract the row minimum from each row.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
minR = min(dMat,[],2);
minC = min(bsxfun(@minus, dMat, minR));
%**************************************************************************
% STEP 2: Find a zero of dMat. If there are no starred zeros in its
% column or row start the zero. Repeat for each zero
%**************************************************************************
zP = dMat == bsxfun(@plus, minC, minR);
starZ = zeros(n,1);
while any(zP(:))
[r,c]=find(zP,1);
starZ(r)=c;
zP(r,:)=false;
zP(:,c)=false;
end
while 1
%**************************************************************************
% STEP 3: Cover each column with a starred zero. If all the columns are
% covered then the matching is maximum
%**************************************************************************
if all(starZ>0)
break
end
coverColumn = false(1,n);
coverColumn(starZ(starZ>0))=true;
coverRow = false(n,1);
primeZ = zeros(n,1);
[rIdx, cIdx] = find(dMat(~coverRow,~coverColumn)==bsxfun(@plus,minR(~coverRow),minC(~coverColumn)));
while 1
%**************************************************************************
% STEP 4: Find a noncovered zero and prime it. If there is no starred
% zero in the row containing this primed zero, Go to Step 5.
% Otherwise, cover this row and uncover the column containing
% the starred zero. Continue in this manner until there are no
% uncovered zeros left. Save the smallest uncovered value and
% Go to Step 6.
%**************************************************************************
cR = find(~coverRow);
cC = find(~coverColumn);
rIdx = cR(rIdx);
cIdx = cC(cIdx);
Step = 6;
while ~isempty(cIdx)
uZr = rIdx(1);
uZc = cIdx(1);
primeZ(uZr) = uZc;
stz = starZ(uZr);
if ~stz
Step = 5;
break;
end
coverRow(uZr) = true;
coverColumn(stz) = false;
z = rIdx==uZr;
rIdx(z) = [];
cIdx(z) = [];
cR = find(~coverRow);
z = dMat(~coverRow,stz) == minR(~coverRow) + minC(stz);
rIdx = [rIdx(:);cR(z)];
cIdx = [cIdx(:);stz(ones(sum(z),1))];
end
if Step == 6
% *************************************************************************
% STEP 6: Add the minimum uncovered value to every element of each covered
% row, and subtract it from every element of each uncovered column.
% Return to Step 4 without altering any stars, primes, or covered lines.
%**************************************************************************
[minval,rIdx,cIdx]=outerplus(dMat(~coverRow,~coverColumn),minR(~coverRow),minC(~coverColumn));
minC(~coverColumn) = minC(~coverColumn) + minval;
minR(coverRow) = minR(coverRow) – minval;
else
break
end
end
%**************************************************************************
% STEP 5:
% Construct a series of alternating primed and starred zeros as
% follows:
% Let Z0 represent the uncovered primed zero found in Step 4.
% Let Z1 denote the starred zero in the column of Z0 (if any).
% Let Z2 denote the primed zero in the row of Z1 (there will always
% be one). Continue until the series terminates at a primed zero
% that has no starred zero in its column. Unstar each starred
% zero of the series, star each primed zero of the series, erase
% all primes and uncover every line in the matrix. Return to Step 3.
%**************************************************************************
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
while rowZ1>0
starZ(rowZ1)=0;
uZc = primeZ(rowZ1);
uZr = rowZ1;
rowZ1 = find(starZ==uZc);
starZ(uZr)=uZc;
end
end
% Cost of assignment
rowIdx = find(validRow);
colIdx = find(validCol);
starZ = starZ(1:nRows);
vIdx = starZ <= nCols;
assignment(rowIdx(vIdx)) = colIdx(starZ(vIdx));
cost = trace(costMat(assignment>0,assignment(assignment>0)));
function [minval,rIdx,cIdx]=outerplus(M,x,y)
[nx,ny]=size(M);
minval=inf;
for r=1:nx
x1=x(r);
for c=1:ny
M(r,c)=M(r,c)-(x1+y(c));
if minval>M(r,c)
minval=M(r,c);
end
end
end
[rIdx,cIdx]=find(M==minval);
This code is from SPECTRAL METHODS IN MATLAB by Trefethen. The eigenvalue problem is solved here. But for t>0, how can I calculate eigenvalues? . Dont hasitate to ask me any questien if my problem was mis understood. Thanks in advance. eigenvalues, orr-sommerfeld operator, numarical, chebysheb MATLAB Answers — New Questions
About a csv file from matlab 2018
Can anyone share the weatherReports.csv file from matlab 2018??Can anyone share the weatherReports.csv file from matlab 2018?? Can anyone share the weatherReports.csv file from matlab 2018?? matlab 2018, csv fil, whetherreports MATLAB Answers — New Questions
RL Training Slows Down With Full Experience Buffer
I’m working on an RL project using a DQN agent with a custom environment. I tried training the agent without an LSTM layer with limited success and now I’m trying with an LSTM layer. I very quickly noticed that after the experience buffer is filled, i.e. the Total Number of Steps counter reaches the ExperienceBuffer length set in the agent properties, the training slows to a crawl. Where the first several training episodes complete in seconds, once this value of total steps is reached the next episode takes several minutes to train, and future ones don’t seem to recover the speed. This hasn’t happened in all my iterations of the agent and learning settings before I enabled the LSTM layer.
I’m wondering if this is expected behavior, why this might be happening given my settings, etc. My agent options are below, more details can be given if needed. Thanks!
agentOpts = rlDQNAgentOptions;
agentOpts.SequenceLength = 16;
agentOpts.MiniBatchSize = 100; % grab 100 "trajectories" of length 16 from the buffer at a time for training
agentOpts.NumStepsToLookAhead = 1; % forced for LSTM enabled critics
agentOpts.ExperienceBufferLength = 10000; % once the total steps reaches this number, training slows down dramatically
The critic network setup is:
ObservationInfo = rlNumericSpec([16 1]); % 16 tile game board
ActionInfo = rlFiniteSetSpec([1 2 3 4]); % 4 possible actions per turn
% Input Layer
layers = [
sequenceInputLayer(16, "Name", "input_1")
fullyConnectedLayer(1024,"Name","fc_1", "WeightsInitializer", "he")
reluLayer("Name","relu_body")
];
% Body Hidden Layers
for i = 1:3
layers = [layers
fullyConnectedLayer(1024,"Name", join(["fc_" num2str(i)]), "WeightsInitializer", "he")
reluLayer("Name", join(["body_output_" num2str(i)]))
];
end
% LSTM Layer
layers = [layers
lstmLayer(1024,"Name","lstm", "InputWeightsInitializer", "he", "RecurrentWeightsInitializer", "he")
];
% Output Layer
layers = [layers
fullyConnectedLayer(4,"Name","fc_action")
regressionLayer("Name","output")
];
dqnCritic = rlQValueRepresentation(layers, ObservationInfo, ActionInfo, "Observation", "input_1");I’m working on an RL project using a DQN agent with a custom environment. I tried training the agent without an LSTM layer with limited success and now I’m trying with an LSTM layer. I very quickly noticed that after the experience buffer is filled, i.e. the Total Number of Steps counter reaches the ExperienceBuffer length set in the agent properties, the training slows to a crawl. Where the first several training episodes complete in seconds, once this value of total steps is reached the next episode takes several minutes to train, and future ones don’t seem to recover the speed. This hasn’t happened in all my iterations of the agent and learning settings before I enabled the LSTM layer.
I’m wondering if this is expected behavior, why this might be happening given my settings, etc. My agent options are below, more details can be given if needed. Thanks!
agentOpts = rlDQNAgentOptions;
agentOpts.SequenceLength = 16;
agentOpts.MiniBatchSize = 100; % grab 100 "trajectories" of length 16 from the buffer at a time for training
agentOpts.NumStepsToLookAhead = 1; % forced for LSTM enabled critics
agentOpts.ExperienceBufferLength = 10000; % once the total steps reaches this number, training slows down dramatically
The critic network setup is:
ObservationInfo = rlNumericSpec([16 1]); % 16 tile game board
ActionInfo = rlFiniteSetSpec([1 2 3 4]); % 4 possible actions per turn
% Input Layer
layers = [
sequenceInputLayer(16, "Name", "input_1")
fullyConnectedLayer(1024,"Name","fc_1", "WeightsInitializer", "he")
reluLayer("Name","relu_body")
];
% Body Hidden Layers
for i = 1:3
layers = [layers
fullyConnectedLayer(1024,"Name", join(["fc_" num2str(i)]), "WeightsInitializer", "he")
reluLayer("Name", join(["body_output_" num2str(i)]))
];
end
% LSTM Layer
layers = [layers
lstmLayer(1024,"Name","lstm", "InputWeightsInitializer", "he", "RecurrentWeightsInitializer", "he")
];
% Output Layer
layers = [layers
fullyConnectedLayer(4,"Name","fc_action")
regressionLayer("Name","output")
];
dqnCritic = rlQValueRepresentation(layers, ObservationInfo, ActionInfo, "Observation", "input_1"); I’m working on an RL project using a DQN agent with a custom environment. I tried training the agent without an LSTM layer with limited success and now I’m trying with an LSTM layer. I very quickly noticed that after the experience buffer is filled, i.e. the Total Number of Steps counter reaches the ExperienceBuffer length set in the agent properties, the training slows to a crawl. Where the first several training episodes complete in seconds, once this value of total steps is reached the next episode takes several minutes to train, and future ones don’t seem to recover the speed. This hasn’t happened in all my iterations of the agent and learning settings before I enabled the LSTM layer.
I’m wondering if this is expected behavior, why this might be happening given my settings, etc. My agent options are below, more details can be given if needed. Thanks!
agentOpts = rlDQNAgentOptions;
agentOpts.SequenceLength = 16;
agentOpts.MiniBatchSize = 100; % grab 100 "trajectories" of length 16 from the buffer at a time for training
agentOpts.NumStepsToLookAhead = 1; % forced for LSTM enabled critics
agentOpts.ExperienceBufferLength = 10000; % once the total steps reaches this number, training slows down dramatically
The critic network setup is:
ObservationInfo = rlNumericSpec([16 1]); % 16 tile game board
ActionInfo = rlFiniteSetSpec([1 2 3 4]); % 4 possible actions per turn
% Input Layer
layers = [
sequenceInputLayer(16, "Name", "input_1")
fullyConnectedLayer(1024,"Name","fc_1", "WeightsInitializer", "he")
reluLayer("Name","relu_body")
];
% Body Hidden Layers
for i = 1:3
layers = [layers
fullyConnectedLayer(1024,"Name", join(["fc_" num2str(i)]), "WeightsInitializer", "he")
reluLayer("Name", join(["body_output_" num2str(i)]))
];
end
% LSTM Layer
layers = [layers
lstmLayer(1024,"Name","lstm", "InputWeightsInitializer", "he", "RecurrentWeightsInitializer", "he")
];
% Output Layer
layers = [layers
fullyConnectedLayer(4,"Name","fc_action")
regressionLayer("Name","output")
];
dqnCritic = rlQValueRepresentation(layers, ObservationInfo, ActionInfo, "Observation", "input_1"); rldqnagent, experience buffer, training speed, rnn MATLAB Answers — New Questions
Plotting mutiple measurement Data with counter
Hello together,
i would like to plot my measurements data 66 signals over time in one plot.
However i wrote a counter that i dont have to deal with 66 signals.
How can i plot now all this data in one plot using my counter?
My Script
% 28 or 33 C with 2 sensors each
for iC = 1:numOfC
for iTempOfC = 1:2
signalNameCTemp = sprintf("CC_%02i_Temperatur_%01i", iC, iTempOfC);
idxTemp = (iC – 1) * 2 + iTempOfC; %sub2ind([3,2],2,2)
plot (m.t, all signals of the 66 sensors)
So far I only get 1 signal in my plot.
Thank you guys.Hello together,
i would like to plot my measurements data 66 signals over time in one plot.
However i wrote a counter that i dont have to deal with 66 signals.
How can i plot now all this data in one plot using my counter?
My Script
% 28 or 33 C with 2 sensors each
for iC = 1:numOfC
for iTempOfC = 1:2
signalNameCTemp = sprintf("CC_%02i_Temperatur_%01i", iC, iTempOfC);
idxTemp = (iC – 1) * 2 + iTempOfC; %sub2ind([3,2],2,2)
plot (m.t, all signals of the 66 sensors)
So far I only get 1 signal in my plot.
Thank you guys. Hello together,
i would like to plot my measurements data 66 signals over time in one plot.
However i wrote a counter that i dont have to deal with 66 signals.
How can i plot now all this data in one plot using my counter?
My Script
% 28 or 33 C with 2 sensors each
for iC = 1:numOfC
for iTempOfC = 1:2
signalNameCTemp = sprintf("CC_%02i_Temperatur_%01i", iC, iTempOfC);
idxTemp = (iC – 1) * 2 + iTempOfC; %sub2ind([3,2],2,2)
plot (m.t, all signals of the 66 sensors)
So far I only get 1 signal in my plot.
Thank you guys. plot, for loop, counter, graph, database MATLAB Answers — New Questions
SQL Profiler: can I see values of a proc when it is called from another proc?
I have SQL Server 2012 Enterprise. I have run SQL Profiler to track calls of my stored procedures. I have specified SP:Starting event for this.
There was a situation when my client application calls a procedure Proc1; and Proc1 calls procedure Proc2. Profiler displays the both calls – OK. But I see that Profiler displays actual values of procedure parameters (“@param1 = xxx, @param2= yyy” etc) only for Proc1. For Proc2 it does not show the actual values; it just enlists the parameters (“@param1, @param2” etc).
Is there a way to make SQL Profiler display the actual values for Proc2? Or maybe some other (free) profiler can do this?
I have SQL Server 2012 Enterprise. I have run SQL Profiler to track calls of my stored procedures. I have specified SP:Starting event for this.There was a situation when my client application calls a procedure Proc1; and Proc1 calls procedure Proc2. Profiler displays the both calls – OK. But I see that Profiler displays actual values of procedure parameters (“@param1 = xxx, @param2= yyy” etc) only for Proc1. For Proc2 it does not show the actual values; it just enlists the parameters (“@param1, @param2” etc). Is there a way to make SQL Profiler display the actual values for Proc2? Or maybe some other (free) profiler can do this? Read More
AVD Session host health state ‘Unavailable’
Hi Team,
We have Azure VD and some of the VMs/session hosts have ‘power state,’ as running but ‘Health State’ is ‘Unavailable’. Pls. find the screen shot attached with more details.
Is it possible to fix it by using ‘redeploy’ + reapply’ option? We have no data on the VM as its pooled and not dedicated. Any other solution, pls. suggest.
Regards,
Hi Team, We have Azure VD and some of the VMs/session hosts have ‘power state,’ as running but ‘Health State’ is ‘Unavailable’. Pls. find the screen shot attached with more details. Is it possible to fix it by using ‘redeploy’ + reapply’ option? We have no data on the VM as its pooled and not dedicated. Any other solution, pls. suggest. Regards, Read More
Some sort of a sumif formula
Hello,
I have an issue with a formula i can’t figure out how to make it work,
My goal is to apply a summ in a cell (A1 equals A2 for example) but ONLY if 2 specific cells have any data inside, text, numbers, summs, etc,
for example, A3 equals A2 ONLY if A2 and A1 have text/data/formula inside.
What would the formula be ?
Hello, I have an issue with a formula i can’t figure out how to make it work, My goal is to apply a summ in a cell (A1 equals A2 for example) but ONLY if 2 specific cells have any data inside, text, numbers, summs, etc, for example, A3 equals A2 ONLY if A2 and A1 have text/data/formula inside. What would the formula be ? Read More
Migration sql server from sql 2017 to sql 2022 with Minimal Down time
Below is our suggestion for the migration activity:
Always on High Availability
DB Mirroring
Logshipping
SQL Always on High Availability :
It is possible to configure a SQL Server Always On availability group with a primary replica running on SQL Server 2017 and a secondary replica running on SQL Server 2022, but there are important considerations and limitations to keep in mind:
Backward Compatibility: SQL Server supports having replicas on different versions, but the primary replica must be on an older version than or equal to the secondary replicas. Therefore, having SQL Server 2017 as the primary and SQL Server 2022 as the secondary is valid.
Database Upgrade Path: When you decide to upgrade the primary replica to a newer version, you need to follow a specific upgrade path to ensure minimal downtime and data integrity. Typically, this involves:
Adding the newer version as a secondary replica.
Failing over to the secondary replica running the newer version (making it the new primary).
Upgrading the former primary to the newer version.
Adding it back to the availability group.
Feature Compatibility: Some features available in SQL Server 2022 might not be fully supported or behave differently when the primary replica is running on SQL Server 2017. It’s essential to test the behavior of your applications and workloads thoroughly in this mixed-version environment.
Support and Documentation: Always refer to the official Microsoft documentation for the most accurate and up-to-date information about version compatibility and supported configurations. Microsoft’s official [documentation on Always On availability groups](https://docs.microsoft.com/en-us/sql/database-engine/availability-groups/windows/always-on-availability-groups-sql-server?view=sql-server-ver15) is a good place to start.
Licensing and Maintenance: Ensure that your licensing agreements and maintenance plans support such a configuration. Running different versions might have implications for your support agreements with Microsoft.
Here is a high-level example of setting up such a configuration:
Install SQL Server 2017 on the primary server and configure it as the primary replica.
Install SQL Server 2022 on the secondary server and configure it as the secondary replica.
Create the availability group on SQL Server 2017 and add the database(s) to the group.
Add the SQL Server 2022 instance as a secondary replica to the availability group.
Configure synchronization and verify that the secondary replica is properly synchronized with the primary replica.
Example Steps for Adding SQL Server 2022 as a Secondary Replica
On the Primary Server (SQL Server 2017):
ALTER AVAILABILITY GROUP [YourAGName]
ADD REPLICA ON ‘SQL2022ServerName’
WITH (ENDPOINT_URL = ‘TCP://SQL2022ServerName:5022’, AVAILABILITY_MODE = ASYNCHRONOUS_COMMIT, FAILOVER_MODE = MANUAL);
On the Secondary Server (SQL Server 2022):
ALTER DATABASE [YourDatabaseName] SET HADR AVAILABILITY GROUP = YourAGName;
Join the Secondary Replica to the Availability Group:
ALTER AVAILABILITY GROUP [YourAGName] JOIN;
Start Data Synchronization:
ALTER DATABASE [YourDatabaseName] SET HADR RESUME;
Always test such configurations in a non-production environment to ensure that everything works as expected and to understand any potential issues or performance implications.
DB Mirroring :
Using database mirroring to migrate a SQL Server database from SQL Server 2017 to SQL Server 2022 is a viable strategy. Database mirroring provides a way to maintain a synchronized copy of your database on the new server. Here are the detailed steps to perform the migration:
Step-by-Step Migration Process
Prepare the Environment
Install SQL Server 2022: Set up SQL Server 2022 on your new server where you want to migrate your database.
Network Configuration: Ensure that the network between the old (SQL Server 2017) and the new server (SQL Server 2022) is properly configured and both servers can communicate with each other.
Backup the Primary Database
Full Backup:
BACKUP DATABASE YourDatabaseName TO DISK = ‘C:BackupYourDatabaseName_Full.bak’;
Transaction Log Backup:
BACKUP LOG YourDatabaseName TO DISK = ‘C:BackupYourDatabaseName_Log.trn’;
Restore the Backup on the New Server
Copy the backup files to the new server.
Restore the Full Backup:
RESTORE DATABASE YourDatabaseName FROM DISK = ‘C:BackupYourDatabaseName_Full.bak’
WITH NORECOVERY;
Restore the Transaction Log Backup:
RESTORE LOG YourDatabaseName FROM DISK = ‘C:BackupYourDatabaseName_Log.trn’
WITH NORECOVERY;
Configure Database Mirroring
On the Principal (SQL Server 2017):
ALTER DATABASE YourDatabaseName
SET PARTNER = ‘TCP://SQL2022ServerName:5022’;
On the Mirror (SQL Server 2022):
ALTER DATABASE YourDatabaseName
SET PARTNER = ‘TCP://SQL2017ServerName:5022’;
Security Configuration: Ensure that the database mirroring endpoints are configured correctly and that the service accounts have the necessary permissions.
Monitor the Synchronization
Verify that the mirroring session is established and that the databases are synchronizing. You can use the following query to check the status:
SELECT
db_name(database_id) AS DatabaseName,
mirroring_state_desc,
mirroring_role_desc,
mirroring_partner_name,
mirroring_partner_instance
FROM
sys.database_mirroring;
Failover to the New Server (SQL Server 2022)
Once the database is fully synchronized, you can perform a manual failover to make the SQL Server 2022 instance the principal server.
ALTER DATABASE YourDatabaseName SET PARTNER FAILOVER;
Update Applications and Services
Point your applications and services to the new SQL Server 2022 instance.
Update connection strings to reflect the new server name or IP address.
Remove Mirroring (Optional)
If you no longer need mirroring after the migration, you can remove the mirroring configuration.
— On the Principal (now SQL Server 2022)
ALTER DATABASE YourDatabaseName SET PARTNER OFF;
— On the Mirror (SQL Server 2017)
ALTER DATABASE YourDatabaseName SET PARTNER OFF;
Considerations and Best Practices
Compatibility: Ensure that your database and applications are compatible with SQL Server 2022. Test in a non-production environment before migrating.
Downtime: Plan for a maintenance window, as there might be a brief downtime during the failover.
Backup and Restore: Always have a recent backup before starting the migration.
Using database mirroring can provide a smooth transition with minimal downtime, ensuring that your data remains consistent throughout the migration process.
Log Shippig :
Using log shipping to upgrade from SQL Server 2017 to SQL Server 2022 involves setting up log shipping between the two servers, synchronizing them, and then performing a cutover. Here are the steps to perform the migration using log shipping:
Step-by-Step Migration Process
Prepare the Environment
Install SQL Server 2022: Set up SQL Server 2022 on your new server.
Network Configuration: Ensure that the network between the old (SQL Server 2017) and the new server (SQL Server 2022) is properly configured and both servers can communicate with each other.
Configure Log Shipping
Full Backup of the Primary Database (SQL Server 2017):
BACKUP DATABASE YourDatabaseName TO DISK = ‘C:BackupYourDatabaseName_Full.bak’;
Copy the Full Backup to the new server (SQL Server 2022).
Restore the Full Backup on the New Server (SQL Server 2022):
RESTORE DATABASE YourDatabaseName FROM DISK = ‘C:BackupYourDatabaseName_Full.bak’
WITH NORECOVERY;
Enable Log Shipping on the Primary Database (SQL Server 2017):
Right-click the database in SQL Server Management Studio (SSMS), go to “Properties,” and select “Transaction Log Shipping.”
Check “Enable this as a primary database in a log shipping configuration.”
Configure the backup settings (backup path, schedule).
Configure the Secondary Server (SQL Server 2022):
Specify the new server as the secondary.
Set the path to the backup folder where transaction log backups will be copied.
Configure the restore settings to restore the logs with the `STANDBY` option (so the database can be read-only for verification purposes) or `NORECOVERY` (if you want to keep it in a restoring state).
Start Log Shipping
Initial Transaction Log Backup:
BACKUP LOG YourDatabaseName TO DISK = ‘C:BackupYourDatabaseName_Log1.trn’;
Copy and Restore the Log Backup on SQL Server 2022:
RESTORE LOG YourDatabaseName FROM DISK = ‘C:BackupYourDatabaseName_Log1.trn’
WITH NORECOVERY;
Schedule Regular Log Backups: Configure SQL Server Agent jobs to take regular transaction log backups on the primary and copy them to the secondary server.
Monitor Log Shipping
– Monitor the log shipping status using the Log Shipping Monitor or SQL Server Management Studio to ensure that the transaction logs are being backed up, copied, and restored correctly.
Perform the Cutover to SQL Server 2022
Stop All Transactions on the Primary Database (SQL Server 2017): Ensure no new transactions are occurring on the primary database.
ALTER DATABASE YourDatabaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
Take a Final Log Backup on the Primary (SQL Server 2017):
BACKUP LOG YourDatabaseName TO DISK = ‘C:BackupYourDatabaseName_LogFinal.trn’;
Copy and Restore the Final Log Backup on the Secondary (SQL Server 2022):
RESTORE LOG YourDatabaseName FROM DISK = ‘C:BackupYourDatabaseName_LogFinal.trn’
WITH RECOVERY;
Bring the New Database Online:
ALTER DATABASE YourDatabaseName SET MULTI_USER;
Update Applications and Services
Point your applications and services to the new SQL Server 2022 instance.
Update connection strings to reflect the new server name or IP address.
Considerations and Best Practices
Testing: Thoroughly test the log shipping configuration and the final cutover process in a non-production environment before doing it in production.
Downtime: Plan for a maintenance window during the cutover process as there will be some downtime.
Backup and Restore: Always have recent backups before starting the migration.
Log Shipping Monitor: Use the Log Shipping Monitor to ensure that all log shipping processes are running smoothly.
Log shipping for the upgrade provides a way to minimize downtime and ensure data consistency throughout the migration process.
Microsoft Tech Community – Latest Blogs –Read More
Cancel parfeval causes workers to throw errors
I’m writing a GUI in App Designer to run Simulink simulations in parallel, using parfeval because I need the ability to cancel in-progress tasks. The app has an Abort button that sets a global variable when it is pressed, which the fetchNext loop checks for. The function myFunc runs the Simulink models and does a lot of extra setup and processing as well. Here’s some abbreviated code:
% get or create pool
pool = gcp;
% schedule tasks
futures(1:numIterations) = parallel.FevalFuture;
for p = 1:numIterations
futures(p) = parfeval(@myFunc);
end
% collect results
numCompleted = 0;
timeout = 180; % 3 minute timeout
while numCompleted < numIterations
[completedIdx, results] = fetchNext(futures,timeout);
numCompleted = numCompleted + 1;
% collect results from tasks that didn’t time out
if ~isempty(completedIdx)
workerTasks{completedIdx} = results;
end
% check for abort
if app.abortRequested
break;
end
end
% check for abort
if app.abortRequested
cancel(pool.FevalQueue.QueuedFutures);
cancel(pool.FevalQueue.RunningFutures);
end
This runs fine, and the abort feature works the first time you use it.
Then if you immediately run the code again, several of the tasks come back Failed with the error message "Dot indexing is not supported for variables of this type." If you close down the pool and re-run the program with fresh workers, the problem disappears.
It seems like cancel doesn’t fully delete the job from the threads, and there’s something left over that interferes with new tasks. Has anyone run into this? Am I missing a step when canceling the futures?
Thanks in advance.I’m writing a GUI in App Designer to run Simulink simulations in parallel, using parfeval because I need the ability to cancel in-progress tasks. The app has an Abort button that sets a global variable when it is pressed, which the fetchNext loop checks for. The function myFunc runs the Simulink models and does a lot of extra setup and processing as well. Here’s some abbreviated code:
% get or create pool
pool = gcp;
% schedule tasks
futures(1:numIterations) = parallel.FevalFuture;
for p = 1:numIterations
futures(p) = parfeval(@myFunc);
end
% collect results
numCompleted = 0;
timeout = 180; % 3 minute timeout
while numCompleted < numIterations
[completedIdx, results] = fetchNext(futures,timeout);
numCompleted = numCompleted + 1;
% collect results from tasks that didn’t time out
if ~isempty(completedIdx)
workerTasks{completedIdx} = results;
end
% check for abort
if app.abortRequested
break;
end
end
% check for abort
if app.abortRequested
cancel(pool.FevalQueue.QueuedFutures);
cancel(pool.FevalQueue.RunningFutures);
end
This runs fine, and the abort feature works the first time you use it.
Then if you immediately run the code again, several of the tasks come back Failed with the error message "Dot indexing is not supported for variables of this type." If you close down the pool and re-run the program with fresh workers, the problem disappears.
It seems like cancel doesn’t fully delete the job from the threads, and there’s something left over that interferes with new tasks. Has anyone run into this? Am I missing a step when canceling the futures?
Thanks in advance. I’m writing a GUI in App Designer to run Simulink simulations in parallel, using parfeval because I need the ability to cancel in-progress tasks. The app has an Abort button that sets a global variable when it is pressed, which the fetchNext loop checks for. The function myFunc runs the Simulink models and does a lot of extra setup and processing as well. Here’s some abbreviated code:
% get or create pool
pool = gcp;
% schedule tasks
futures(1:numIterations) = parallel.FevalFuture;
for p = 1:numIterations
futures(p) = parfeval(@myFunc);
end
% collect results
numCompleted = 0;
timeout = 180; % 3 minute timeout
while numCompleted < numIterations
[completedIdx, results] = fetchNext(futures,timeout);
numCompleted = numCompleted + 1;
% collect results from tasks that didn’t time out
if ~isempty(completedIdx)
workerTasks{completedIdx} = results;
end
% check for abort
if app.abortRequested
break;
end
end
% check for abort
if app.abortRequested
cancel(pool.FevalQueue.QueuedFutures);
cancel(pool.FevalQueue.RunningFutures);
end
This runs fine, and the abort feature works the first time you use it.
Then if you immediately run the code again, several of the tasks come back Failed with the error message "Dot indexing is not supported for variables of this type." If you close down the pool and re-run the program with fresh workers, the problem disappears.
It seems like cancel doesn’t fully delete the job from the threads, and there’s something left over that interferes with new tasks. Has anyone run into this? Am I missing a step when canceling the futures?
Thanks in advance. parfeval, appdesigner, parallel.fevalfuture, parallel computing toolbox, cancel MATLAB Answers — New Questions
Display of errorbar function in plot legend
Hi
I am annoyed about a line going through the errorbar symbol in my legend. I have tried to make a dummy plot for handles, ploting it prior to all other plots with lines in them, but it does not change anything. I can not find any information about it in the documentation and I was not able to find any other treads where this was complained about and obviously not any solution either. I attached an image below since it is a bit hard to explain. Thanks a lot!
This is how I ploted the errorbar
errorbar(mean(x1),mean(y1),sdy1,sdy1,sdx1,sdx1,’k’)Hi
I am annoyed about a line going through the errorbar symbol in my legend. I have tried to make a dummy plot for handles, ploting it prior to all other plots with lines in them, but it does not change anything. I can not find any information about it in the documentation and I was not able to find any other treads where this was complained about and obviously not any solution either. I attached an image below since it is a bit hard to explain. Thanks a lot!
This is how I ploted the errorbar
errorbar(mean(x1),mean(y1),sdy1,sdy1,sdx1,sdx1,’k’) Hi
I am annoyed about a line going through the errorbar symbol in my legend. I have tried to make a dummy plot for handles, ploting it prior to all other plots with lines in them, but it does not change anything. I can not find any information about it in the documentation and I was not able to find any other treads where this was complained about and obviously not any solution either. I attached an image below since it is a bit hard to explain. Thanks a lot!
This is how I ploted the errorbar
errorbar(mean(x1),mean(y1),sdy1,sdy1,sdx1,sdx1,’k’) legend, errorbar, plot MATLAB Answers — New Questions
Model of a matrix
How can I model the matrix of full permutation [(1,1,0,…,0) (-1,-1,0,…,0)] for n variables.How can I model the matrix of full permutation [(1,1,0,…,0) (-1,-1,0,…,0)] for n variables. How can I model the matrix of full permutation [(1,1,0,…,0) (-1,-1,0,…,0)] for n variables. matrix, permutation MATLAB Answers — New Questions
Fluent UI Theme Designer – SharePoint theme assistance
Good day
I created a new theme for my site collection using Fluent UI Theme Designer and it looks ok. However, the icons on the landing page look odd with black as a title colour. How can I change this to colour white? Please help.
Good day I created a new theme for my site collection using Fluent UI Theme Designer and it looks ok. However, the icons on the landing page look odd with black as a title colour. How can I change this to colour white? Please help. Read More