Category: Matlab
Category Archives: Matlab
Common factor
Is there a function to make it find a common factor in an expression with symbolic variables?
For example:
ab+ac–(matlab command)—>a(b+c)
ThanksIs there a function to make it find a common factor in an expression with symbolic variables?
For example:
ab+ac–(matlab command)—>a(b+c)
Thanks Is there a function to make it find a common factor in an expression with symbolic variables?
For example:
ab+ac–(matlab command)—>a(b+c)
Thanks matlab, factor MATLAB Answers — New Questions
How to make a text file from functions
x = 1
y = 1
myFile = fopen(‘myValues.txt’, ‘w’)
fprintf(myFile, "X LengthtY Lengtht Hypot LengthttPerimeterttArean")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "ttt" + string(j) + "tttt" + string(myHypot) + "ttt" + string(myPerim) + "ttt" + string(myArea) + "n")
end
end
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
endx = 1
y = 1
myFile = fopen(‘myValues.txt’, ‘w’)
fprintf(myFile, "X LengthtY Lengtht Hypot LengthttPerimeterttArean")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "ttt" + string(j) + "tttt" + string(myHypot) + "ttt" + string(myPerim) + "ttt" + string(myArea) + "n")
end
end
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
end x = 1
y = 1
myFile = fopen(‘myValues.txt’, ‘w’)
fprintf(myFile, "X LengthtY Lengtht Hypot LengthttPerimeterttArean")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "ttt" + string(j) + "tttt" + string(myHypot) + "ttt" + string(myPerim) + "ttt" + string(myArea) + "n")
end
end
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
end matlab MATLAB Answers — New Questions
How to write all cells of structure in excel sheet ?
Hello all,
I have variable which has 1×1 structure, and this structure has many field (it can be reached to 200). each field has has diffrent size of cells as explained in the images.
I want to write the results in excel sheel. like in the uploaded image:
my code is:
writematrix (‘Day’,’Results_Theta.xlsx’,’WriteMode’,’replacefile’,’Sheet’,’Theta’,’Range’,’A1′);
writematrix (‘Theta 1′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’B1′);
writematrix (‘Theta 2′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’C1′);
writematrix (‘Theta 3′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’D1′);
writematrix (‘Theta 4′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’E1′);
writematrix (‘Theta 5′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’F1′);
writematrix (‘Theta 6′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’G1′);
writematrix (‘Theta 7′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’H1′);
So, how can I write the results?Hello all,
I have variable which has 1×1 structure, and this structure has many field (it can be reached to 200). each field has has diffrent size of cells as explained in the images.
I want to write the results in excel sheel. like in the uploaded image:
my code is:
writematrix (‘Day’,’Results_Theta.xlsx’,’WriteMode’,’replacefile’,’Sheet’,’Theta’,’Range’,’A1′);
writematrix (‘Theta 1′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’B1′);
writematrix (‘Theta 2′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’C1′);
writematrix (‘Theta 3′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’D1′);
writematrix (‘Theta 4′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’E1′);
writematrix (‘Theta 5′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’F1′);
writematrix (‘Theta 6′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’G1′);
writematrix (‘Theta 7′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’H1′);
So, how can I write the results? Hello all,
I have variable which has 1×1 structure, and this structure has many field (it can be reached to 200). each field has has diffrent size of cells as explained in the images.
I want to write the results in excel sheel. like in the uploaded image:
my code is:
writematrix (‘Day’,’Results_Theta.xlsx’,’WriteMode’,’replacefile’,’Sheet’,’Theta’,’Range’,’A1′);
writematrix (‘Theta 1′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’B1′);
writematrix (‘Theta 2′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’C1′);
writematrix (‘Theta 3′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’D1′);
writematrix (‘Theta 4′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’E1′);
writematrix (‘Theta 5′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’F1′);
writematrix (‘Theta 6′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’G1′);
writematrix (‘Theta 7′,’Results_Theta.xlsx’,’Sheet’,’Theta’,’Range’,’H1′);
So, how can I write the results? writematrix MATLAB Answers — New Questions
How to declare constants and vector as argument for once to use it in multiple functions
Dear all;
In my matlab code i have a parent code called "Main SDM". This code call child function "Child WSO" several time and then this child code call its child "single_dd" several time (about 100 times) which in its place call a child function "Ipv_newton" 3000 time!
The problem is that the two last functions are time consuming since it call each time their and constants and vectors
I want to global this constants and vectors or call it for once in Main SDM: ( Im,V, K,q, T, VT_stc) using input argument till the last function!
How it is possible to do it in multi stage (declare variable in main code and than use input argument for first function and continue until last function !)
Is it possible to do so, If not, what is the best way for my code’s performance
function J = single_dd(X)
global V Ie Im
J1=0;
Im=[0.7645 ……………………………….0.212 0.1035 -0.01 -0.123 -0.21];
V=[-0.2057 -0.1291 -0.0588 ………………. 0.5521 0.5633 0.5736 0.5833 0.59];
function x=Ipv_newton(X,v,x0)
k=1.38064852e-23;
q=1.60217646e-19;
T=33+273.15;
Vt_stc=k*T/q;
Main SDM call Child WSO which call single_dd which call Ipv_newtonDear all;
In my matlab code i have a parent code called "Main SDM". This code call child function "Child WSO" several time and then this child code call its child "single_dd" several time (about 100 times) which in its place call a child function "Ipv_newton" 3000 time!
The problem is that the two last functions are time consuming since it call each time their and constants and vectors
I want to global this constants and vectors or call it for once in Main SDM: ( Im,V, K,q, T, VT_stc) using input argument till the last function!
How it is possible to do it in multi stage (declare variable in main code and than use input argument for first function and continue until last function !)
Is it possible to do so, If not, what is the best way for my code’s performance
function J = single_dd(X)
global V Ie Im
J1=0;
Im=[0.7645 ……………………………….0.212 0.1035 -0.01 -0.123 -0.21];
V=[-0.2057 -0.1291 -0.0588 ………………. 0.5521 0.5633 0.5736 0.5833 0.59];
function x=Ipv_newton(X,v,x0)
k=1.38064852e-23;
q=1.60217646e-19;
T=33+273.15;
Vt_stc=k*T/q;
Main SDM call Child WSO which call single_dd which call Ipv_newton Dear all;
In my matlab code i have a parent code called "Main SDM". This code call child function "Child WSO" several time and then this child code call its child "single_dd" several time (about 100 times) which in its place call a child function "Ipv_newton" 3000 time!
The problem is that the two last functions are time consuming since it call each time their and constants and vectors
I want to global this constants and vectors or call it for once in Main SDM: ( Im,V, K,q, T, VT_stc) using input argument till the last function!
How it is possible to do it in multi stage (declare variable in main code and than use input argument for first function and continue until last function !)
Is it possible to do so, If not, what is the best way for my code’s performance
function J = single_dd(X)
global V Ie Im
J1=0;
Im=[0.7645 ……………………………….0.212 0.1035 -0.01 -0.123 -0.21];
V=[-0.2057 -0.1291 -0.0588 ………………. 0.5521 0.5633 0.5736 0.5833 0.59];
function x=Ipv_newton(X,v,x0)
k=1.38064852e-23;
q=1.60217646e-19;
T=33+273.15;
Vt_stc=k*T/q;
Main SDM call Child WSO which call single_dd which call Ipv_newton performance, profiler, function, global variables, input argument, vector MATLAB Answers — New Questions
Simulink to see Fourier
I have a very simple task but am not being successful.
I have a PWM generator in simulike runing at a certain frequency and certain duty cycle.
I want to take the fourier analysis of it and plot it in a scope.
What i expect to see is the DC component of the perioid signal… (i think?)
So if i have a period signal PWM signal with a magnitude of say 5 and duty cycle of .5 i expect to see a DC of 2.5 out on my scope.
How can i acomplish this? I have tried a few different blocks in simulink but im not getting what im expecting.
Perhaps my expecatations are wrong.I have a very simple task but am not being successful.
I have a PWM generator in simulike runing at a certain frequency and certain duty cycle.
I want to take the fourier analysis of it and plot it in a scope.
What i expect to see is the DC component of the perioid signal… (i think?)
So if i have a period signal PWM signal with a magnitude of say 5 and duty cycle of .5 i expect to see a DC of 2.5 out on my scope.
How can i acomplish this? I have tried a few different blocks in simulink but im not getting what im expecting.
Perhaps my expecatations are wrong. I have a very simple task but am not being successful.
I have a PWM generator in simulike runing at a certain frequency and certain duty cycle.
I want to take the fourier analysis of it and plot it in a scope.
What i expect to see is the DC component of the perioid signal… (i think?)
So if i have a period signal PWM signal with a magnitude of say 5 and duty cycle of .5 i expect to see a DC of 2.5 out on my scope.
How can i acomplish this? I have tried a few different blocks in simulink but im not getting what im expecting.
Perhaps my expecatations are wrong. simulink, fourier MATLAB Answers — New Questions
Imgradient3 function: can we used this function for finding chnage in gradient of surface points.
I generated coordinates by converting 3d image to stl. Now I want to give the x coordinates, y coordinates and z coordinates of all the ponts as input in imgradient3 function. Means instead of Gx, Gy and Gz can we put Intx, Inty and Intz in that function. intx isx coordinates of all the genrated points using surface meshing. I am interested in finding the change in gradient of all the points with respect to their neighbours.I generated coordinates by converting 3d image to stl. Now I want to give the x coordinates, y coordinates and z coordinates of all the ponts as input in imgradient3 function. Means instead of Gx, Gy and Gz can we put Intx, Inty and Intz in that function. intx isx coordinates of all the genrated points using surface meshing. I am interested in finding the change in gradient of all the points with respect to their neighbours. I generated coordinates by converting 3d image to stl. Now I want to give the x coordinates, y coordinates and z coordinates of all the ponts as input in imgradient3 function. Means instead of Gx, Gy and Gz can we put Intx, Inty and Intz in that function. intx isx coordinates of all the genrated points using surface meshing. I am interested in finding the change in gradient of all the points with respect to their neighbours. imgradient3, gradient, change in gradient MATLAB Answers — New Questions
Accessing a vector form a matrix
Hi, I am writing a solver scipt where I will have outputed 3 vectors called x1, x2, and x3. I then plan to turn these into a 3 x (some value tbd) vector, meaning x=[x1, x2, x3].
In the main script I need to plot x1, x2 and x3 independently, which brings me to my question. How do I call, for instance, the x1 vector from the ‘x’ matrix so I can plot it please?Hi, I am writing a solver scipt where I will have outputed 3 vectors called x1, x2, and x3. I then plan to turn these into a 3 x (some value tbd) vector, meaning x=[x1, x2, x3].
In the main script I need to plot x1, x2 and x3 independently, which brings me to my question. How do I call, for instance, the x1 vector from the ‘x’ matrix so I can plot it please? Hi, I am writing a solver scipt where I will have outputed 3 vectors called x1, x2, and x3. I then plan to turn these into a 3 x (some value tbd) vector, meaning x=[x1, x2, x3].
In the main script I need to plot x1, x2 and x3 independently, which brings me to my question. How do I call, for instance, the x1 vector from the ‘x’ matrix so I can plot it please? matrix, vector, callback MATLAB Answers — New Questions
Error in AWGN Using Integers or scalar doubles
Need help correcting the following errors:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in awgn (line 157)
y = sig + noise;
Error in Computerassignmentfinal (line 20)
received_low = awgn(lenna_bits, SNR_low,’measured’);
The code attached.
clc;
clear all;
% Load the lenna image
lenna = imread(‘lenna.png’);
% Convert image to grayscale
lenna_gray = rgb2gray(lenna);
% Convert pixel values to bits
lenna_bits = reshape(de2bi(lenna_gray), [], 1);
% BPSK modulation
Eb_No_low = 0; % Low SNR
Eb_No_high = 4; % High SNR
SNR_low = 10^(Eb_No_low/10);
SNR_high = 10^(Eb_No_high/10);
% Transmit and receive at low SNR
received_low = awgn(lenna_bits, SNR_low,’measured’);
% Demodulation
decoded_low = received_low < 0;
% Reshape decoded bits to original image size
decoded_image_low = reshape(decoded_low, size(lenna_gray));
% Plot original and received image at low SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_low); title(‘Received Image (0 dB SNR)’);
% Transmit and receive at high SNR
received_high = awgn(lenna_bits, SNR_high, ‘measured’);
% Demodulation
decoded_high = received_high < 0;
% Reshape decoded bits to original image size
decoded_image_high = reshape(decoded_high, size(lenna_gray));
% Plot original and received image at high SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_high); title(‘Received Image (4 dB SNR)’);
% Linear error detection code
% Example: Hamming (7,4) code
parityMatrix = [1 1 1 0 1 0 0; 1 1 0 1 0 1 0; 1 0 1 1 0 0 1];
generatorMatrix = [eye(4) parityMatrix’];
% Encode the data
encoded_data = mod(lenna_bits * generatorMatrix, 2);
% Add noise
received_data = awgn(encoded_data, Eb_No_low, ‘measured’);
% Syndrome lookup table for error detection
syndrome_table = syndtable(parityMatrix);
% Decoding with error detection
decoded_data = zeros(size(encoded_data));
errors = zeros(size(encoded_data, 1), 1);
for i = 1:size(encoded_data, 1)
syndrome = mod(received_data(i, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(i) = 1;
else
decoded_data(i, 🙂 = received_data(i, :);
end
end
% Count number of retransmission requests at different SNRs
SNRs = [0, 2, 4, 6, 8, 10];
retransmissions = zeros(size(SNRs));
for i = 1:length(SNRs)
SNR = 10^(SNRs(i)/10);
received_data = awgn(encoded_data, SNR, ‘measured’);
errors = zeros(size(encoded_data, 1), 1);
for j = 1:size(encoded_data, 1)
syndrome = mod(received_data(j, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(j) = 1;
retransmissions(i) = retransmissions(i) + 1;
end
end
end
% Plot number of retransmissions against SNR values
figure;
plot(SNRs, retransmissions, ‘-o’);
xlabel(‘SNR (dB)’);
ylabel(‘Number of Retransmissions’);
title(‘Number of Retransmissions vs SNR’);
% Error correction code
% Example: Reed-Solomon code
n = 255;
k = 223;
t = 16;
rs_encoder = comm.RSEncoder(n, k);
rs_decoder = comm.RSDecoder(n, k);
% Encode data
encoded_rs = step(rs_encoder, double(lenna_bits));
% Add noise
received_rs_low = awgn(encoded_rs, Eb_No_low, ‘measured’);
received_rs_high = awgn(encoded_rs, Eb_No_high, ‘measured’);
% Decode received data
decoded_rs_low = step(rs_decoder, received_rs_low);
decoded_rs_high = step(rs_decoder, received_rs_high);
% Reshape decoded bits to original image size
decoded_image_rs_low = reshape(decoded_rs_low, size(lenna_gray));
decoded_image_rs_high = reshape(decoded_rs_high, size(lenna_gray));
% Plot original and received images with error correction
figure;
subplot(1,2,1); imshow(decoded_image_low); title(‘Received Image (0 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_low); title(‘Received Image (0 dB SNR, Error Correction)’);
figure;
subplot(1,2,1); imshow(decoded_image_high); title(‘Received Image (4 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_high); title(‘Received Image (4 dB SNR, Error Correction)’);Need help correcting the following errors:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in awgn (line 157)
y = sig + noise;
Error in Computerassignmentfinal (line 20)
received_low = awgn(lenna_bits, SNR_low,’measured’);
The code attached.
clc;
clear all;
% Load the lenna image
lenna = imread(‘lenna.png’);
% Convert image to grayscale
lenna_gray = rgb2gray(lenna);
% Convert pixel values to bits
lenna_bits = reshape(de2bi(lenna_gray), [], 1);
% BPSK modulation
Eb_No_low = 0; % Low SNR
Eb_No_high = 4; % High SNR
SNR_low = 10^(Eb_No_low/10);
SNR_high = 10^(Eb_No_high/10);
% Transmit and receive at low SNR
received_low = awgn(lenna_bits, SNR_low,’measured’);
% Demodulation
decoded_low = received_low < 0;
% Reshape decoded bits to original image size
decoded_image_low = reshape(decoded_low, size(lenna_gray));
% Plot original and received image at low SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_low); title(‘Received Image (0 dB SNR)’);
% Transmit and receive at high SNR
received_high = awgn(lenna_bits, SNR_high, ‘measured’);
% Demodulation
decoded_high = received_high < 0;
% Reshape decoded bits to original image size
decoded_image_high = reshape(decoded_high, size(lenna_gray));
% Plot original and received image at high SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_high); title(‘Received Image (4 dB SNR)’);
% Linear error detection code
% Example: Hamming (7,4) code
parityMatrix = [1 1 1 0 1 0 0; 1 1 0 1 0 1 0; 1 0 1 1 0 0 1];
generatorMatrix = [eye(4) parityMatrix’];
% Encode the data
encoded_data = mod(lenna_bits * generatorMatrix, 2);
% Add noise
received_data = awgn(encoded_data, Eb_No_low, ‘measured’);
% Syndrome lookup table for error detection
syndrome_table = syndtable(parityMatrix);
% Decoding with error detection
decoded_data = zeros(size(encoded_data));
errors = zeros(size(encoded_data, 1), 1);
for i = 1:size(encoded_data, 1)
syndrome = mod(received_data(i, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(i) = 1;
else
decoded_data(i, 🙂 = received_data(i, :);
end
end
% Count number of retransmission requests at different SNRs
SNRs = [0, 2, 4, 6, 8, 10];
retransmissions = zeros(size(SNRs));
for i = 1:length(SNRs)
SNR = 10^(SNRs(i)/10);
received_data = awgn(encoded_data, SNR, ‘measured’);
errors = zeros(size(encoded_data, 1), 1);
for j = 1:size(encoded_data, 1)
syndrome = mod(received_data(j, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(j) = 1;
retransmissions(i) = retransmissions(i) + 1;
end
end
end
% Plot number of retransmissions against SNR values
figure;
plot(SNRs, retransmissions, ‘-o’);
xlabel(‘SNR (dB)’);
ylabel(‘Number of Retransmissions’);
title(‘Number of Retransmissions vs SNR’);
% Error correction code
% Example: Reed-Solomon code
n = 255;
k = 223;
t = 16;
rs_encoder = comm.RSEncoder(n, k);
rs_decoder = comm.RSDecoder(n, k);
% Encode data
encoded_rs = step(rs_encoder, double(lenna_bits));
% Add noise
received_rs_low = awgn(encoded_rs, Eb_No_low, ‘measured’);
received_rs_high = awgn(encoded_rs, Eb_No_high, ‘measured’);
% Decode received data
decoded_rs_low = step(rs_decoder, received_rs_low);
decoded_rs_high = step(rs_decoder, received_rs_high);
% Reshape decoded bits to original image size
decoded_image_rs_low = reshape(decoded_rs_low, size(lenna_gray));
decoded_image_rs_high = reshape(decoded_rs_high, size(lenna_gray));
% Plot original and received images with error correction
figure;
subplot(1,2,1); imshow(decoded_image_low); title(‘Received Image (0 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_low); title(‘Received Image (0 dB SNR, Error Correction)’);
figure;
subplot(1,2,1); imshow(decoded_image_high); title(‘Received Image (4 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_high); title(‘Received Image (4 dB SNR, Error Correction)’); Need help correcting the following errors:
Error using +
Integers can only be combined with integers of the same class, or scalar doubles.
Error in awgn (line 157)
y = sig + noise;
Error in Computerassignmentfinal (line 20)
received_low = awgn(lenna_bits, SNR_low,’measured’);
The code attached.
clc;
clear all;
% Load the lenna image
lenna = imread(‘lenna.png’);
% Convert image to grayscale
lenna_gray = rgb2gray(lenna);
% Convert pixel values to bits
lenna_bits = reshape(de2bi(lenna_gray), [], 1);
% BPSK modulation
Eb_No_low = 0; % Low SNR
Eb_No_high = 4; % High SNR
SNR_low = 10^(Eb_No_low/10);
SNR_high = 10^(Eb_No_high/10);
% Transmit and receive at low SNR
received_low = awgn(lenna_bits, SNR_low,’measured’);
% Demodulation
decoded_low = received_low < 0;
% Reshape decoded bits to original image size
decoded_image_low = reshape(decoded_low, size(lenna_gray));
% Plot original and received image at low SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_low); title(‘Received Image (0 dB SNR)’);
% Transmit and receive at high SNR
received_high = awgn(lenna_bits, SNR_high, ‘measured’);
% Demodulation
decoded_high = received_high < 0;
% Reshape decoded bits to original image size
decoded_image_high = reshape(decoded_high, size(lenna_gray));
% Plot original and received image at high SNR
figure;
subplot(1,2,1); imshow(lenna_gray); title(‘Original Image’);
subplot(1,2,2); imshow(decoded_image_high); title(‘Received Image (4 dB SNR)’);
% Linear error detection code
% Example: Hamming (7,4) code
parityMatrix = [1 1 1 0 1 0 0; 1 1 0 1 0 1 0; 1 0 1 1 0 0 1];
generatorMatrix = [eye(4) parityMatrix’];
% Encode the data
encoded_data = mod(lenna_bits * generatorMatrix, 2);
% Add noise
received_data = awgn(encoded_data, Eb_No_low, ‘measured’);
% Syndrome lookup table for error detection
syndrome_table = syndtable(parityMatrix);
% Decoding with error detection
decoded_data = zeros(size(encoded_data));
errors = zeros(size(encoded_data, 1), 1);
for i = 1:size(encoded_data, 1)
syndrome = mod(received_data(i, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(i) = 1;
else
decoded_data(i, 🙂 = received_data(i, :);
end
end
% Count number of retransmission requests at different SNRs
SNRs = [0, 2, 4, 6, 8, 10];
retransmissions = zeros(size(SNRs));
for i = 1:length(SNRs)
SNR = 10^(SNRs(i)/10);
received_data = awgn(encoded_data, SNR, ‘measured’);
errors = zeros(size(encoded_data, 1), 1);
for j = 1:size(encoded_data, 1)
syndrome = mod(received_data(j, 🙂 * parityMatrix’, 2);
if sum(syndrome) ~= 0 % Error detected
errors(j) = 1;
retransmissions(i) = retransmissions(i) + 1;
end
end
end
% Plot number of retransmissions against SNR values
figure;
plot(SNRs, retransmissions, ‘-o’);
xlabel(‘SNR (dB)’);
ylabel(‘Number of Retransmissions’);
title(‘Number of Retransmissions vs SNR’);
% Error correction code
% Example: Reed-Solomon code
n = 255;
k = 223;
t = 16;
rs_encoder = comm.RSEncoder(n, k);
rs_decoder = comm.RSDecoder(n, k);
% Encode data
encoded_rs = step(rs_encoder, double(lenna_bits));
% Add noise
received_rs_low = awgn(encoded_rs, Eb_No_low, ‘measured’);
received_rs_high = awgn(encoded_rs, Eb_No_high, ‘measured’);
% Decode received data
decoded_rs_low = step(rs_decoder, received_rs_low);
decoded_rs_high = step(rs_decoder, received_rs_high);
% Reshape decoded bits to original image size
decoded_image_rs_low = reshape(decoded_rs_low, size(lenna_gray));
decoded_image_rs_high = reshape(decoded_rs_high, size(lenna_gray));
% Plot original and received images with error correction
figure;
subplot(1,2,1); imshow(decoded_image_low); title(‘Received Image (0 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_low); title(‘Received Image (0 dB SNR, Error Correction)’);
figure;
subplot(1,2,1); imshow(decoded_image_high); title(‘Received Image (4 dB SNR, No Error Correction)’);
subplot(1,2,2); imshow(decoded_image_rs_high); title(‘Received Image (4 dB SNR, Error Correction)’); error corrections MATLAB Answers — New Questions
When I use Turkish characters in comments, they turn into question marks when I reopen the file
When I use Turkish characters in comments in MATLAB, they turn into question marks when I reopen the file. How can I solve this issue?
I also encounter this problem when using a directory with turkish characters.
I’m using MATLAB 2023B, operating system is Windows 10.When I use Turkish characters in comments in MATLAB, they turn into question marks when I reopen the file. How can I solve this issue?
I also encounter this problem when using a directory with turkish characters.
I’m using MATLAB 2023B, operating system is Windows 10. When I use Turkish characters in comments in MATLAB, they turn into question marks when I reopen the file. How can I solve this issue?
I also encounter this problem when using a directory with turkish characters.
I’m using MATLAB 2023B, operating system is Windows 10. language, characters, encoding MATLAB Answers — New Questions
how to solve my problem that i write
I write this code and i wanne output that show me like a sinc function like picture that i attached. the other point is about my l value that i defined it, i wanne some random number between 11e-6 till 13e-6, is it true like this that i define?
tnx.
clc;
clear;
close all;
capital_lambda = 20e-6;
% define sellmier equation to obtain refractive index
lambda_sh=0.775e-6; % SH wavelength
nlithium_sh = 2.1784;
lambda_ff=1.55e-6; % FF wavelength
nlithium_ff = 2.1376;
% parameters
capital_lambda = 20e-6;
k_sh=(2*pi/lambda_sh)*nlithium_sh;
k_ff=(2*pi/lambda_ff)*nlithium_ff;
Delta_kk = k_sh-2*k_ff;
%km=2*pi/capital_lambda;
L = 1; % Length;
sigma_l = 2; % sigma_l = l*sigma_avg
N=L/(capital_lambda/2); % number of domains
l=unifrnd(11e-6,13e-6,[1,1000]); %
for i=l
f=exp(-(pi.^2) .* (sigma_l.^2)/2.*(l.^2));
Delta_k=(k_sh-2*k_ff)-pi./l;
E3= f .* (sinc((Delta_k .* L)/2)).^2 + ((1-f)/N);
end
plot(E3)
%plot(abs(fftshift(fft2(E3))))
xlabel(‘(Delta_k * L)/pi’);
ylabel(‘SHG Effiency’);I write this code and i wanne output that show me like a sinc function like picture that i attached. the other point is about my l value that i defined it, i wanne some random number between 11e-6 till 13e-6, is it true like this that i define?
tnx.
clc;
clear;
close all;
capital_lambda = 20e-6;
% define sellmier equation to obtain refractive index
lambda_sh=0.775e-6; % SH wavelength
nlithium_sh = 2.1784;
lambda_ff=1.55e-6; % FF wavelength
nlithium_ff = 2.1376;
% parameters
capital_lambda = 20e-6;
k_sh=(2*pi/lambda_sh)*nlithium_sh;
k_ff=(2*pi/lambda_ff)*nlithium_ff;
Delta_kk = k_sh-2*k_ff;
%km=2*pi/capital_lambda;
L = 1; % Length;
sigma_l = 2; % sigma_l = l*sigma_avg
N=L/(capital_lambda/2); % number of domains
l=unifrnd(11e-6,13e-6,[1,1000]); %
for i=l
f=exp(-(pi.^2) .* (sigma_l.^2)/2.*(l.^2));
Delta_k=(k_sh-2*k_ff)-pi./l;
E3= f .* (sinc((Delta_k .* L)/2)).^2 + ((1-f)/N);
end
plot(E3)
%plot(abs(fftshift(fft2(E3))))
xlabel(‘(Delta_k * L)/pi’);
ylabel(‘SHG Effiency’); I write this code and i wanne output that show me like a sinc function like picture that i attached. the other point is about my l value that i defined it, i wanne some random number between 11e-6 till 13e-6, is it true like this that i define?
tnx.
clc;
clear;
close all;
capital_lambda = 20e-6;
% define sellmier equation to obtain refractive index
lambda_sh=0.775e-6; % SH wavelength
nlithium_sh = 2.1784;
lambda_ff=1.55e-6; % FF wavelength
nlithium_ff = 2.1376;
% parameters
capital_lambda = 20e-6;
k_sh=(2*pi/lambda_sh)*nlithium_sh;
k_ff=(2*pi/lambda_ff)*nlithium_ff;
Delta_kk = k_sh-2*k_ff;
%km=2*pi/capital_lambda;
L = 1; % Length;
sigma_l = 2; % sigma_l = l*sigma_avg
N=L/(capital_lambda/2); % number of domains
l=unifrnd(11e-6,13e-6,[1,1000]); %
for i=l
f=exp(-(pi.^2) .* (sigma_l.^2)/2.*(l.^2));
Delta_k=(k_sh-2*k_ff)-pi./l;
E3= f .* (sinc((Delta_k .* L)/2)).^2 + ((1-f)/N);
end
plot(E3)
%plot(abs(fftshift(fft2(E3))))
xlabel(‘(Delta_k * L)/pi’);
ylabel(‘SHG Effiency’); sinc function, hann window, rectangle, fft, shg effiency MATLAB Answers — New Questions
Setting Maximum Array Size Threshold in Simulink Model for Embedded C Code Generation
Hi,
I am trying to understand how to set maximum size arrays threshold in case of a Simulink model that needs to use Matlab functions that support variable size arrays.
Is "Maximum stack size (bytes)" the proper parameter to set? I am asking this since I have to generate a C code for my model for an embedded application and I need to be sure to set an upper threshold for all the variables inside my model.Hi,
I am trying to understand how to set maximum size arrays threshold in case of a Simulink model that needs to use Matlab functions that support variable size arrays.
Is "Maximum stack size (bytes)" the proper parameter to set? I am asking this since I have to generate a C code for my model for an embedded application and I need to be sure to set an upper threshold for all the variables inside my model. Hi,
I am trying to understand how to set maximum size arrays threshold in case of a Simulink model that needs to use Matlab functions that support variable size arrays.
Is "Maximum stack size (bytes)" the proper parameter to set? I am asking this since I have to generate a C code for my model for an embedded application and I need to be sure to set an upper threshold for all the variables inside my model. code generation, optimization MATLAB Answers — New Questions
Why is it that Line objects can be instances of two different classes? How can I use findobj to detect only chart primitives?
Using findobj, I have ended up with two arrays of Line graphics handles,
load handleArrays
hL
hD
However, the arrays do not appear to belong to a common class,
whos hL hD
Moreover, even though hD clearly has all the same properties as hL, it cannot be accessed with standard indexing, e.g.,
isprop(hD(1),’Color’)
hD.Color
What is the function of these two different handle graphics types, and how do I tell findobj to retrieve only the hL kind and not the hD kind?Using findobj, I have ended up with two arrays of Line graphics handles,
load handleArrays
hL
hD
However, the arrays do not appear to belong to a common class,
whos hL hD
Moreover, even though hD clearly has all the same properties as hL, it cannot be accessed with standard indexing, e.g.,
isprop(hD(1),’Color’)
hD.Color
What is the function of these two different handle graphics types, and how do I tell findobj to retrieve only the hL kind and not the hD kind? Using findobj, I have ended up with two arrays of Line graphics handles,
load handleArrays
hL
hD
However, the arrays do not appear to belong to a common class,
whos hL hD
Moreover, even though hD clearly has all the same properties as hL, it cannot be accessed with standard indexing, e.g.,
isprop(hD(1),’Color’)
hD.Color
What is the function of these two different handle graphics types, and how do I tell findobj to retrieve only the hL kind and not the hD kind? graphics, line, handles MATLAB Answers — New Questions
How to plot the Unit Step response of a transfer function?
I would like to kindly ask how do I plot the Unit Step response, when given the transfer function.
For instance C = any simple transfer function
How would I plot the Unit Step response of this Transfer Function on any given axes
Many thanks in advance.I would like to kindly ask how do I plot the Unit Step response, when given the transfer function.
For instance C = any simple transfer function
How would I plot the Unit Step response of this Transfer Function on any given axes
Many thanks in advance. I would like to kindly ask how do I plot the Unit Step response, when given the transfer function.
For instance C = any simple transfer function
How would I plot the Unit Step response of this Transfer Function on any given axes
Many thanks in advance. unit step response, plotting MATLAB Answers — New Questions
How to add Get function to the Simulink model generated code
Hello,
I’m generation code from the Simulink model (2 inputs, three outpus). I’d like to add Get function for the output(s), e.g.:
RLS_OnOff LGTC_getRearLightOn(void)
{
return strVarRear.enuRearLightOn;
}
I tried it using Access Data Through Functions with Storage Class GetSet but not successfuly. In the Code Mapping, Data Defaults ribon, I updated Storage class for updates to the "GetSet". But during the code generation I received the folloiwng error message:
In model code mappings, default storage class for outports is set to ‘GetSet’, making generated code noncompliant with function prototype control feature. Set default storage class to ‘Default’.
If I update it to Default to get rid of the error Get function is not created.
Does anybody know how to update the Code generation setting/code mapping to sucessfully build the model to get code containing the Get function for the output?
Thank you very much in advanceHello,
I’m generation code from the Simulink model (2 inputs, three outpus). I’d like to add Get function for the output(s), e.g.:
RLS_OnOff LGTC_getRearLightOn(void)
{
return strVarRear.enuRearLightOn;
}
I tried it using Access Data Through Functions with Storage Class GetSet but not successfuly. In the Code Mapping, Data Defaults ribon, I updated Storage class for updates to the "GetSet". But during the code generation I received the folloiwng error message:
In model code mappings, default storage class for outports is set to ‘GetSet’, making generated code noncompliant with function prototype control feature. Set default storage class to ‘Default’.
If I update it to Default to get rid of the error Get function is not created.
Does anybody know how to update the Code generation setting/code mapping to sucessfully build the model to get code containing the Get function for the output?
Thank you very much in advance Hello,
I’m generation code from the Simulink model (2 inputs, three outpus). I’d like to add Get function for the output(s), e.g.:
RLS_OnOff LGTC_getRearLightOn(void)
{
return strVarRear.enuRearLightOn;
}
I tried it using Access Data Through Functions with Storage Class GetSet but not successfuly. In the Code Mapping, Data Defaults ribon, I updated Storage class for updates to the "GetSet". But during the code generation I received the folloiwng error message:
In model code mappings, default storage class for outports is set to ‘GetSet’, making generated code noncompliant with function prototype control feature. Set default storage class to ‘Default’.
If I update it to Default to get rid of the error Get function is not created.
Does anybody know how to update the Code generation setting/code mapping to sucessfully build the model to get code containing the Get function for the output?
Thank you very much in advance code generation, getset MATLAB Answers — New Questions
Does there exists a built in block in Simulink audio tool to design analog electronic PCB with feedback mechanism ?
Adaptive Filters are core of the ANC system. They continuously adjusts its filter coefficients to minimize the error signal, effectively generating the anti-noise signal. Common choices include the Least Mean Squares (LMS) or Normalized LMS (NLMS) algorithms implemented using the respective Simulink blocks. However if the Anti-noise algorithm is analog electronic PCB with feedback mechanism, then does there exists a built in block in Simulink audio tool to design this algorithm?Adaptive Filters are core of the ANC system. They continuously adjusts its filter coefficients to minimize the error signal, effectively generating the anti-noise signal. Common choices include the Least Mean Squares (LMS) or Normalized LMS (NLMS) algorithms implemented using the respective Simulink blocks. However if the Anti-noise algorithm is analog electronic PCB with feedback mechanism, then does there exists a built in block in Simulink audio tool to design this algorithm? Adaptive Filters are core of the ANC system. They continuously adjusts its filter coefficients to minimize the error signal, effectively generating the anti-noise signal. Common choices include the Least Mean Squares (LMS) or Normalized LMS (NLMS) algorithms implemented using the respective Simulink blocks. However if the Anti-noise algorithm is analog electronic PCB with feedback mechanism, then does there exists a built in block in Simulink audio tool to design this algorithm? simulink, signal flow, acoustic path, active noise cancellation earmuff MATLAB Answers — New Questions
Experiences with release 2012b
Did you try 2012b already? What do you like, what has still potential for further improvements, what makes working with Matlab harder than with earlier releases?
How large is the overlap between the new features and the list of wished changes: <http://www.mathworks.com/matlabcentral/answers/1325-what-is-missing-from-matlab Answers: what-is-missing-from-matlab>?Did you try 2012b already? What do you like, what has still potential for further improvements, what makes working with Matlab harder than with earlier releases?
How large is the overlap between the new features and the list of wished changes: <http://www.mathworks.com/matlabcentral/answers/1325-what-is-missing-from-matlab Answers: what-is-missing-from-matlab>? Did you try 2012b already? What do you like, what has still potential for further improvements, what makes working with Matlab harder than with earlier releases?
How large is the overlap between the new features and the list of wished changes: <http://www.mathworks.com/matlabcentral/answers/1325-what-is-missing-from-matlab Answers: what-is-missing-from-matlab>? r2012b, matlab 8.0, simulink, prefdir MATLAB Answers — New Questions
Unable to acquire the live (streaming) video h264 over rtsp of my ip camera using the “IP camera acquisition” package on Matlab2020b
I am unable to acquire the live (streaming) video of my ip camera using the “IP camera acquisition” package.
Premise:
(1) Operating System: MacOS Big Sur (11.0.1)
(2) Matlab version: 2020b
(3) Installed package: IP camera acquisition packages
(4) Camera type: Dahua DH-IPC-HFW2431TP-ZAS
(5) Camera datasheet: https://www.dahuasecurity.com/asset/upload/uploads/soft/20191015/DH-IPC-HFW2431T-ZAS-S2-datasheet-1910111.pdf
(6) Protocol communication: https://dahuasg.s3-ap-southeast-1.amazonaws.com/DOR/PUM0001827/Dahua%20Network%20Camera%20Web%203.0_Operation%20Manual_V2.0.7.pdf
(7) Link for rtsp streaming: https://dahuawiki.com/Remote_Access/RTSP_via_VLC
I would like to capture live video from my camera using the rtsp link with H264 codec. I did a lot of testing, but never managed to capture the video stream. The rtsp links I used are (7):
rtsp://admin:admin1993@192.168.0.108:554/cam/realmonitor?channel=1&subtype=0
rtsp: //192.168.0.108: 554/live
Both of these links placed on any browser open VLC correctly and the video stream is regularly captured.
Camera data:
IP address: 192.168.0.108
admin: admin
password: admin1993
RTSP port: 554
Resolution: 1080p (I also tried 720p and other formats)
Bit rate: 4096 kbit / s (I did different tests with different rate)
Below I have reported some of the tests carried out:
cam = ipcam(‘rtsp://admin:admin1993@192.168.0.108:554/cam/realmonitor?channel=1&subtype=0’)
cam = ipcam(‘rtsp://admin:admin1993@192.168.0.108:554/cam/realmonitor?channel=1&subtype=0′,’admin’,’admin1993′)
cam = ipcam(‘rtsp://192.168.0.108:554/live’,’admin’,’admin1993′)
cam = ipcam(‘rtsp://192.168.0.108:554/live’)
I also tried to do some tests by changing the ‘Timeout’ time but to no avail:
cam = ipcam(‘rtsp://192.168.0.108:554/live’,’admin’,’admin1993′,’Timeout’,30)
The error generated is always the same:
Cannot connect to the IP Camera Stream URL. Make sure the URL is correct and authentication is provided if needed.
I have read the PDF guide on the MATLAB website several times and I believe I have made all the correct configurations: https://it.mathworks.com/help/pdf_doc/supportpkg/ipcamera/ipcamera_ug.pdf
Can anyone help me to solve this problem?
I thought it was a codec problem or camera settings everything seems fine. I also leave attached a photo of the characteristics of the video stream.
Many thanks in advanceI am unable to acquire the live (streaming) video of my ip camera using the “IP camera acquisition” package.
Premise:
(1) Operating System: MacOS Big Sur (11.0.1)
(2) Matlab version: 2020b
(3) Installed package: IP camera acquisition packages
(4) Camera type: Dahua DH-IPC-HFW2431TP-ZAS
(5) Camera datasheet: https://www.dahuasecurity.com/asset/upload/uploads/soft/20191015/DH-IPC-HFW2431T-ZAS-S2-datasheet-1910111.pdf
(6) Protocol communication: https://dahuasg.s3-ap-southeast-1.amazonaws.com/DOR/PUM0001827/Dahua%20Network%20Camera%20Web%203.0_Operation%20Manual_V2.0.7.pdf
(7) Link for rtsp streaming: https://dahuawiki.com/Remote_Access/RTSP_via_VLC
I would like to capture live video from my camera using the rtsp link with H264 codec. I did a lot of testing, but never managed to capture the video stream. The rtsp links I used are (7):
rtsp://admin:admin1993@192.168.0.108:554/cam/realmonitor?channel=1&subtype=0
rtsp: //192.168.0.108: 554/live
Both of these links placed on any browser open VLC correctly and the video stream is regularly captured.
Camera data:
IP address: 192.168.0.108
admin: admin
password: admin1993
RTSP port: 554
Resolution: 1080p (I also tried 720p and other formats)
Bit rate: 4096 kbit / s (I did different tests with different rate)
Below I have reported some of the tests carried out:
cam = ipcam(‘rtsp://admin:admin1993@192.168.0.108:554/cam/realmonitor?channel=1&subtype=0’)
cam = ipcam(‘rtsp://admin:admin1993@192.168.0.108:554/cam/realmonitor?channel=1&subtype=0′,’admin’,’admin1993′)
cam = ipcam(‘rtsp://192.168.0.108:554/live’,’admin’,’admin1993′)
cam = ipcam(‘rtsp://192.168.0.108:554/live’)
I also tried to do some tests by changing the ‘Timeout’ time but to no avail:
cam = ipcam(‘rtsp://192.168.0.108:554/live’,’admin’,’admin1993′,’Timeout’,30)
The error generated is always the same:
Cannot connect to the IP Camera Stream URL. Make sure the URL is correct and authentication is provided if needed.
I have read the PDF guide on the MATLAB website several times and I believe I have made all the correct configurations: https://it.mathworks.com/help/pdf_doc/supportpkg/ipcamera/ipcamera_ug.pdf
Can anyone help me to solve this problem?
I thought it was a codec problem or camera settings everything seems fine. I also leave attached a photo of the characteristics of the video stream.
Many thanks in advance I am unable to acquire the live (streaming) video of my ip camera using the “IP camera acquisition” package.
Premise:
(1) Operating System: MacOS Big Sur (11.0.1)
(2) Matlab version: 2020b
(3) Installed package: IP camera acquisition packages
(4) Camera type: Dahua DH-IPC-HFW2431TP-ZAS
(5) Camera datasheet: https://www.dahuasecurity.com/asset/upload/uploads/soft/20191015/DH-IPC-HFW2431T-ZAS-S2-datasheet-1910111.pdf
(6) Protocol communication: https://dahuasg.s3-ap-southeast-1.amazonaws.com/DOR/PUM0001827/Dahua%20Network%20Camera%20Web%203.0_Operation%20Manual_V2.0.7.pdf
(7) Link for rtsp streaming: https://dahuawiki.com/Remote_Access/RTSP_via_VLC
I would like to capture live video from my camera using the rtsp link with H264 codec. I did a lot of testing, but never managed to capture the video stream. The rtsp links I used are (7):
rtsp://admin:admin1993@192.168.0.108:554/cam/realmonitor?channel=1&subtype=0
rtsp: //192.168.0.108: 554/live
Both of these links placed on any browser open VLC correctly and the video stream is regularly captured.
Camera data:
IP address: 192.168.0.108
admin: admin
password: admin1993
RTSP port: 554
Resolution: 1080p (I also tried 720p and other formats)
Bit rate: 4096 kbit / s (I did different tests with different rate)
Below I have reported some of the tests carried out:
cam = ipcam(‘rtsp://admin:admin1993@192.168.0.108:554/cam/realmonitor?channel=1&subtype=0’)
cam = ipcam(‘rtsp://admin:admin1993@192.168.0.108:554/cam/realmonitor?channel=1&subtype=0′,’admin’,’admin1993′)
cam = ipcam(‘rtsp://192.168.0.108:554/live’,’admin’,’admin1993′)
cam = ipcam(‘rtsp://192.168.0.108:554/live’)
I also tried to do some tests by changing the ‘Timeout’ time but to no avail:
cam = ipcam(‘rtsp://192.168.0.108:554/live’,’admin’,’admin1993′,’Timeout’,30)
The error generated is always the same:
Cannot connect to the IP Camera Stream URL. Make sure the URL is correct and authentication is provided if needed.
I have read the PDF guide on the MATLAB website several times and I believe I have made all the correct configurations: https://it.mathworks.com/help/pdf_doc/supportpkg/ipcamera/ipcamera_ug.pdf
Can anyone help me to solve this problem?
I thought it was a codec problem or camera settings everything seems fine. I also leave attached a photo of the characteristics of the video stream.
Many thanks in advance image acquisition MATLAB Answers — New Questions
How to fix this code trying to create 3 seperate plots from a 3D plots exported to png.
This is code to take all fig files from my map and to convert the to a png, with exception of a 3DPlot, which I want to export as 3 different figures for all axis combinations : X-Y X-Z and Y-Z
the Z axis is not found though.
I made most of this code with AI and am a novice when it comes to coding,
As far as I understand its not finding 3 axis, returning i = 1
returning the following error:
Index exceeds the number of array elements (1).
Error in Fig_to_png_Script (line 27)
copyobj(get(axesHandles(2), ‘Children’), ax2);
I added Numel exceptions in order to skip the error in this version so the code runs and creates only the X-Y plot
% Get all .fig files in the current directory
figFiles = dir(‘*.fig’);
% Loop through each .fig file
for i = 1:length(figFiles)
figName = figFiles(i).name;
% Check if it’s a 3D plot
if contains(figName, ‘3DPlot.fig’, ‘IgnoreCase’, true)
% Load the figure
fig = openfig(figName, ‘invisible’);
% Get handle to the axes
axesHandles = findobj(fig, ‘type’, ‘axes’);
% Handle the X-Y plane (axis 1)
if numel(axesHandles) >= 1
newFig = figure;
ax1 = axes(‘Parent’, newFig);
copyobj(get(axesHandles(1), ‘Children’), ax1);
xlabel(ax1, get(get(axesHandles(1), ‘XLabel’), ‘String’));
ylabel(ax1, get(get(axesHandles(1), ‘YLabel’), ‘String’));
[~, figBaseName, ~] = fileparts(figName);
saveas(newFig, [figBaseName ‘_axis_1.png’]);
close(newFig);
end
% Handle the X-Z plane (axis 2)
if numel(axesHandles) >= 2
newFig = figure;
ax2 = axes(‘Parent’, newFig);
copyobj(get(axesHandles(2), ‘Children’), ax2);
xlabel(ax2, get(get(axesHandles(2), ‘XLabel’), ‘String’));
zlabel(ax2, get(get(axesHandles(2), ‘ZLabel’), ‘String’));
[~, figBaseName, ~] = fileparts(figName);
saveas(newFig, [figBaseName ‘_axis_2.png’]);
close(newFig);
end
% Handle the Y-Z plane (axis 3)
if numel(axesHandles) >= 3
newFig = figure;
ax3 = axes(‘Parent’, newFig);
copyobj(get(axesHandles(3), ‘Children’), ax3);
ylabel(ax3, get(get(axesHandles(3), ‘YLabel’), ‘String’));
zlabel(ax3, get(get(axesHandles(3), ‘ZLabel’), ‘String’));
[~, figBaseName, ~] = fileparts(figName);
saveas(newFig, [figBaseName ‘_axis_3.png’]);
close(newFig);
end
else
% Load the figure
fig = openfig(figName);
% Save as PNG
saveas(fig, [figName ‘.png’]);
% Close the figure
close(fig);
end
endThis is code to take all fig files from my map and to convert the to a png, with exception of a 3DPlot, which I want to export as 3 different figures for all axis combinations : X-Y X-Z and Y-Z
the Z axis is not found though.
I made most of this code with AI and am a novice when it comes to coding,
As far as I understand its not finding 3 axis, returning i = 1
returning the following error:
Index exceeds the number of array elements (1).
Error in Fig_to_png_Script (line 27)
copyobj(get(axesHandles(2), ‘Children’), ax2);
I added Numel exceptions in order to skip the error in this version so the code runs and creates only the X-Y plot
% Get all .fig files in the current directory
figFiles = dir(‘*.fig’);
% Loop through each .fig file
for i = 1:length(figFiles)
figName = figFiles(i).name;
% Check if it’s a 3D plot
if contains(figName, ‘3DPlot.fig’, ‘IgnoreCase’, true)
% Load the figure
fig = openfig(figName, ‘invisible’);
% Get handle to the axes
axesHandles = findobj(fig, ‘type’, ‘axes’);
% Handle the X-Y plane (axis 1)
if numel(axesHandles) >= 1
newFig = figure;
ax1 = axes(‘Parent’, newFig);
copyobj(get(axesHandles(1), ‘Children’), ax1);
xlabel(ax1, get(get(axesHandles(1), ‘XLabel’), ‘String’));
ylabel(ax1, get(get(axesHandles(1), ‘YLabel’), ‘String’));
[~, figBaseName, ~] = fileparts(figName);
saveas(newFig, [figBaseName ‘_axis_1.png’]);
close(newFig);
end
% Handle the X-Z plane (axis 2)
if numel(axesHandles) >= 2
newFig = figure;
ax2 = axes(‘Parent’, newFig);
copyobj(get(axesHandles(2), ‘Children’), ax2);
xlabel(ax2, get(get(axesHandles(2), ‘XLabel’), ‘String’));
zlabel(ax2, get(get(axesHandles(2), ‘ZLabel’), ‘String’));
[~, figBaseName, ~] = fileparts(figName);
saveas(newFig, [figBaseName ‘_axis_2.png’]);
close(newFig);
end
% Handle the Y-Z plane (axis 3)
if numel(axesHandles) >= 3
newFig = figure;
ax3 = axes(‘Parent’, newFig);
copyobj(get(axesHandles(3), ‘Children’), ax3);
ylabel(ax3, get(get(axesHandles(3), ‘YLabel’), ‘String’));
zlabel(ax3, get(get(axesHandles(3), ‘ZLabel’), ‘String’));
[~, figBaseName, ~] = fileparts(figName);
saveas(newFig, [figBaseName ‘_axis_3.png’]);
close(newFig);
end
else
% Load the figure
fig = openfig(figName);
% Save as PNG
saveas(fig, [figName ‘.png’]);
% Close the figure
close(fig);
end
end This is code to take all fig files from my map and to convert the to a png, with exception of a 3DPlot, which I want to export as 3 different figures for all axis combinations : X-Y X-Z and Y-Z
the Z axis is not found though.
I made most of this code with AI and am a novice when it comes to coding,
As far as I understand its not finding 3 axis, returning i = 1
returning the following error:
Index exceeds the number of array elements (1).
Error in Fig_to_png_Script (line 27)
copyobj(get(axesHandles(2), ‘Children’), ax2);
I added Numel exceptions in order to skip the error in this version so the code runs and creates only the X-Y plot
% Get all .fig files in the current directory
figFiles = dir(‘*.fig’);
% Loop through each .fig file
for i = 1:length(figFiles)
figName = figFiles(i).name;
% Check if it’s a 3D plot
if contains(figName, ‘3DPlot.fig’, ‘IgnoreCase’, true)
% Load the figure
fig = openfig(figName, ‘invisible’);
% Get handle to the axes
axesHandles = findobj(fig, ‘type’, ‘axes’);
% Handle the X-Y plane (axis 1)
if numel(axesHandles) >= 1
newFig = figure;
ax1 = axes(‘Parent’, newFig);
copyobj(get(axesHandles(1), ‘Children’), ax1);
xlabel(ax1, get(get(axesHandles(1), ‘XLabel’), ‘String’));
ylabel(ax1, get(get(axesHandles(1), ‘YLabel’), ‘String’));
[~, figBaseName, ~] = fileparts(figName);
saveas(newFig, [figBaseName ‘_axis_1.png’]);
close(newFig);
end
% Handle the X-Z plane (axis 2)
if numel(axesHandles) >= 2
newFig = figure;
ax2 = axes(‘Parent’, newFig);
copyobj(get(axesHandles(2), ‘Children’), ax2);
xlabel(ax2, get(get(axesHandles(2), ‘XLabel’), ‘String’));
zlabel(ax2, get(get(axesHandles(2), ‘ZLabel’), ‘String’));
[~, figBaseName, ~] = fileparts(figName);
saveas(newFig, [figBaseName ‘_axis_2.png’]);
close(newFig);
end
% Handle the Y-Z plane (axis 3)
if numel(axesHandles) >= 3
newFig = figure;
ax3 = axes(‘Parent’, newFig);
copyobj(get(axesHandles(3), ‘Children’), ax3);
ylabel(ax3, get(get(axesHandles(3), ‘YLabel’), ‘String’));
zlabel(ax3, get(get(axesHandles(3), ‘ZLabel’), ‘String’));
[~, figBaseName, ~] = fileparts(figName);
saveas(newFig, [figBaseName ‘_axis_3.png’]);
close(newFig);
end
else
% Load the figure
fig = openfig(figName);
% Save as PNG
saveas(fig, [figName ‘.png’]);
% Close the figure
close(fig);
end
end plot, getobj, 3dplot, error MATLAB Answers — New Questions
Is It Possible To Enable The “Fit To Content” Formatting Option For Custom Blocks?
Simulink has a nice feature under the "Format" tab called "Fit To Content" that automatically resizes the block so that the mask fits within the mask. I’d like to be able to use this feature for the custom blocks that I create. Is this possible?Simulink has a nice feature under the "Format" tab called "Fit To Content" that automatically resizes the block so that the mask fits within the mask. I’d like to be able to use this feature for the custom blocks that I create. Is this possible? Simulink has a nice feature under the "Format" tab called "Fit To Content" that automatically resizes the block so that the mask fits within the mask. I’d like to be able to use this feature for the custom blocks that I create. Is this possible? simulink MATLAB Answers — New Questions
Read all lines of binary file at once
Hello! My code currently opens 120 folders one by one and each folder contains 2 binary files. The code then opens each binary file one by one and reads it. These binary files have 1250 lines each and the lines are read once again one by one.
Is it possible to have the code read all of the lines of 1 binary file at once, not go through 1250 lines sequentially?
The format of the first line is ‘int int int int int int’ (6x int) and the format of all other lines is ‘int char float float float float float float’ (1x int, 1x char, 6x float). The code can be found below.
If there are other suggestions for speeding up the code, please do mention them.
listing = dir(ResultsFolder); % Folder with all 120 folders
for i = 1:length(listing) % Goes from 1 to 120
FieldFolder = [listing(i).folder ” listing(i).name]; % Open 1 of the 120 folders
listingFields = dir(FieldFolder);
FieldFiles = listingFields(contains({listingFields.name},sprintf(‘%A.fld’))); % Get the 2 binary files of interest
for j = 1:length(FieldFiles) % Goes from 1 to 2
fileID = fopen([FieldFolder ” FieldFiles(j).name]); % Open binary file
k = 1;
fileEnd = false;
while ~fileEnd % Read all of the 1250 lines
% FirstLineFormat=’int int int int int int’
% OtherLineFormat=’int char float float float float float float’
try
if k == 1
FieldData_tmp(k,:) = [fread(fileID, 6, ‘int’)’ 0 0 ]; % Read first line
else
FieldData_tmp(k,:) = [fread(fileID, 1, ‘int’) fread(fileID, 1, ‘char’) fread(fileID, 6, ‘float’)’]; % Read other lines
end
catch
fileEnd = true; % No lines left
end
k = k+1;
end
fclose(fileID);
end
endHello! My code currently opens 120 folders one by one and each folder contains 2 binary files. The code then opens each binary file one by one and reads it. These binary files have 1250 lines each and the lines are read once again one by one.
Is it possible to have the code read all of the lines of 1 binary file at once, not go through 1250 lines sequentially?
The format of the first line is ‘int int int int int int’ (6x int) and the format of all other lines is ‘int char float float float float float float’ (1x int, 1x char, 6x float). The code can be found below.
If there are other suggestions for speeding up the code, please do mention them.
listing = dir(ResultsFolder); % Folder with all 120 folders
for i = 1:length(listing) % Goes from 1 to 120
FieldFolder = [listing(i).folder ” listing(i).name]; % Open 1 of the 120 folders
listingFields = dir(FieldFolder);
FieldFiles = listingFields(contains({listingFields.name},sprintf(‘%A.fld’))); % Get the 2 binary files of interest
for j = 1:length(FieldFiles) % Goes from 1 to 2
fileID = fopen([FieldFolder ” FieldFiles(j).name]); % Open binary file
k = 1;
fileEnd = false;
while ~fileEnd % Read all of the 1250 lines
% FirstLineFormat=’int int int int int int’
% OtherLineFormat=’int char float float float float float float’
try
if k == 1
FieldData_tmp(k,:) = [fread(fileID, 6, ‘int’)’ 0 0 ]; % Read first line
else
FieldData_tmp(k,:) = [fread(fileID, 1, ‘int’) fread(fileID, 1, ‘char’) fread(fileID, 6, ‘float’)’]; % Read other lines
end
catch
fileEnd = true; % No lines left
end
k = k+1;
end
fclose(fileID);
end
end Hello! My code currently opens 120 folders one by one and each folder contains 2 binary files. The code then opens each binary file one by one and reads it. These binary files have 1250 lines each and the lines are read once again one by one.
Is it possible to have the code read all of the lines of 1 binary file at once, not go through 1250 lines sequentially?
The format of the first line is ‘int int int int int int’ (6x int) and the format of all other lines is ‘int char float float float float float float’ (1x int, 1x char, 6x float). The code can be found below.
If there are other suggestions for speeding up the code, please do mention them.
listing = dir(ResultsFolder); % Folder with all 120 folders
for i = 1:length(listing) % Goes from 1 to 120
FieldFolder = [listing(i).folder ” listing(i).name]; % Open 1 of the 120 folders
listingFields = dir(FieldFolder);
FieldFiles = listingFields(contains({listingFields.name},sprintf(‘%A.fld’))); % Get the 2 binary files of interest
for j = 1:length(FieldFiles) % Goes from 1 to 2
fileID = fopen([FieldFolder ” FieldFiles(j).name]); % Open binary file
k = 1;
fileEnd = false;
while ~fileEnd % Read all of the 1250 lines
% FirstLineFormat=’int int int int int int’
% OtherLineFormat=’int char float float float float float float’
try
if k == 1
FieldData_tmp(k,:) = [fread(fileID, 6, ‘int’)’ 0 0 ]; % Read first line
else
FieldData_tmp(k,:) = [fread(fileID, 1, ‘int’) fread(fileID, 1, ‘char’) fread(fileID, 6, ‘float’)’]; % Read other lines
end
catch
fileEnd = true; % No lines left
end
k = k+1;
end
fclose(fileID);
end
end binary MATLAB Answers — New Questions