Category: Matlab
Category Archives: Matlab
how to convert logical array in arraycell
logical2cellstr not working..there is a similar words reserved?logical2cellstr not working..there is a similar words reserved? logical2cellstr not working..there is a similar words reserved? how to convert logical array in arraycell MATLAB Answers — New Questions
how to use local parameter in HDL Coder toolbox?
Dear MATLAB Support Team,
I am currently working on developing an UART transmitter block in Simulink. Within this block, I require two parameters: CLOCK_FREQ and BAUD_RATE, which are essential for calculating the DIVIDER parameter, given by CLOCK_FREQ / BAUD_RATE.
While I have learned how to generate parameters using HDL Coder, I am facing confusion regarding the generation of the local parameter DIVIDER, which will be utilized within a counter block. I aim to produce Verilog code similar to the following:
– – – – – – – –
parameter BAUD_RATE = 9600;
parameter CLOCK_FREQ = 100000000;
localparam DIVIDER = CLOCK_FREQ / BAUD_RATE;
if (clk_divider == DIVIDER) begin
// Further implementation
end
– – – – – – – – –
However, the generated code I am obtaining differs:
– – – – – – – – – – – –
parameter integer BAUD_RATE = 9600;
parameter integer CLOCK_FREQ = 100000000;
assign DIVIDER_out1 = 32’b00000000000000000010100010110001;
– – – – – – – – – – –
How can I use BAUD_RATE and CLOCK_FREQ within the module to generate other parameters?
The Constant Block setting is as follows:Dear MATLAB Support Team,
I am currently working on developing an UART transmitter block in Simulink. Within this block, I require two parameters: CLOCK_FREQ and BAUD_RATE, which are essential for calculating the DIVIDER parameter, given by CLOCK_FREQ / BAUD_RATE.
While I have learned how to generate parameters using HDL Coder, I am facing confusion regarding the generation of the local parameter DIVIDER, which will be utilized within a counter block. I aim to produce Verilog code similar to the following:
– – – – – – – –
parameter BAUD_RATE = 9600;
parameter CLOCK_FREQ = 100000000;
localparam DIVIDER = CLOCK_FREQ / BAUD_RATE;
if (clk_divider == DIVIDER) begin
// Further implementation
end
– – – – – – – – –
However, the generated code I am obtaining differs:
– – – – – – – – – – – –
parameter integer BAUD_RATE = 9600;
parameter integer CLOCK_FREQ = 100000000;
assign DIVIDER_out1 = 32’b00000000000000000010100010110001;
– – – – – – – – – – –
How can I use BAUD_RATE and CLOCK_FREQ within the module to generate other parameters?
The Constant Block setting is as follows: Dear MATLAB Support Team,
I am currently working on developing an UART transmitter block in Simulink. Within this block, I require two parameters: CLOCK_FREQ and BAUD_RATE, which are essential for calculating the DIVIDER parameter, given by CLOCK_FREQ / BAUD_RATE.
While I have learned how to generate parameters using HDL Coder, I am facing confusion regarding the generation of the local parameter DIVIDER, which will be utilized within a counter block. I aim to produce Verilog code similar to the following:
– – – – – – – –
parameter BAUD_RATE = 9600;
parameter CLOCK_FREQ = 100000000;
localparam DIVIDER = CLOCK_FREQ / BAUD_RATE;
if (clk_divider == DIVIDER) begin
// Further implementation
end
– – – – – – – – –
However, the generated code I am obtaining differs:
– – – – – – – – – – – –
parameter integer BAUD_RATE = 9600;
parameter integer CLOCK_FREQ = 100000000;
assign DIVIDER_out1 = 32’b00000000000000000010100010110001;
– – – – – – – – – – –
How can I use BAUD_RATE and CLOCK_FREQ within the module to generate other parameters?
The Constant Block setting is as follows: hdl coder, simulink, verilog MATLAB Answers — New Questions
Creating MP4 with Audio
Hello
I want to create an MP4 file which contains audio. VideoWriter is not suitable, as it doesn’t input any audio data. So, I used _vision.VideoFileWriter_ and _step_. But I have some problems.
When running the code below:
videoFWriter = vision.VideoFileWriter(‘Test.mp4’, ‘FileFormat’, ‘MPEG4’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
I receive the following warning message:
Warning: The AudioInputPort property is not relevant in this configuration of the System object.
When I change the code to the following, the video format is uncompressed AVI, which leads to huge file sizes.
videoFWriter = vision.VideoFileWriter(‘Test.avi’, ‘FileFormat’, ‘AVI’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
step(videoFWriter, FrameScreen, FrameAudio);
_FrameAudio_ contains audio data corresponding to one video frame. It seems that it ignores ‘MJPEG Compressor’.
I would love to be able to directly create .mp4 files, but if not possible, it is fine with me to create good quality compressed .avi files, and use a 3rd party software to convert to .mp4. I would appreciate any suggestions. Thanks.
My OS is Windows 7, and MATLAB r2017b.
Cheers
Amir-HomayounHello
I want to create an MP4 file which contains audio. VideoWriter is not suitable, as it doesn’t input any audio data. So, I used _vision.VideoFileWriter_ and _step_. But I have some problems.
When running the code below:
videoFWriter = vision.VideoFileWriter(‘Test.mp4’, ‘FileFormat’, ‘MPEG4’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
I receive the following warning message:
Warning: The AudioInputPort property is not relevant in this configuration of the System object.
When I change the code to the following, the video format is uncompressed AVI, which leads to huge file sizes.
videoFWriter = vision.VideoFileWriter(‘Test.avi’, ‘FileFormat’, ‘AVI’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
step(videoFWriter, FrameScreen, FrameAudio);
_FrameAudio_ contains audio data corresponding to one video frame. It seems that it ignores ‘MJPEG Compressor’.
I would love to be able to directly create .mp4 files, but if not possible, it is fine with me to create good quality compressed .avi files, and use a 3rd party software to convert to .mp4. I would appreciate any suggestions. Thanks.
My OS is Windows 7, and MATLAB r2017b.
Cheers
Amir-Homayoun Hello
I want to create an MP4 file which contains audio. VideoWriter is not suitable, as it doesn’t input any audio data. So, I used _vision.VideoFileWriter_ and _step_. But I have some problems.
When running the code below:
videoFWriter = vision.VideoFileWriter(‘Test.mp4’, ‘FileFormat’, ‘MPEG4’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
I receive the following warning message:
Warning: The AudioInputPort property is not relevant in this configuration of the System object.
When I change the code to the following, the video format is uncompressed AVI, which leads to huge file sizes.
videoFWriter = vision.VideoFileWriter(‘Test.avi’, ‘FileFormat’, ‘AVI’, ‘FrameRate’, 30, ‘AudioInputPort’, true);
videoFWriter.VideoCompressor = ‘MJPEG Compressor’;
step(videoFWriter, FrameScreen, FrameAudio);
_FrameAudio_ contains audio data corresponding to one video frame. It seems that it ignores ‘MJPEG Compressor’.
I would love to be able to directly create .mp4 files, but if not possible, it is fine with me to create good quality compressed .avi files, and use a 3rd party software to convert to .mp4. I would appreciate any suggestions. Thanks.
My OS is Windows 7, and MATLAB r2017b.
Cheers
Amir-Homayoun mp4, audio, compression, video, avi, movie, mpeg4, videofilewriter, videowriter, sound MATLAB Answers — New Questions
roadrunner logic editor PID control
In the Roadrunner logic editor, is there a way to control PID using parameter values already obtained through optimization?In the Roadrunner logic editor, is there a way to control PID using parameter values already obtained through optimization? In the Roadrunner logic editor, is there a way to control PID using parameter values already obtained through optimization? roadrunner, logiceditor MATLAB Answers — New Questions
normpdf is taking zeros
Hello, I am using the normpdf command to evaluate a function in MATLAB. When the argument of normpdf is too small, MATLAB reports a zero. Is is possible to get the exact value of normpdf instead of 0?Hello, I am using the normpdf command to evaluate a function in MATLAB. When the argument of normpdf is too small, MATLAB reports a zero. Is is possible to get the exact value of normpdf instead of 0? Hello, I am using the normpdf command to evaluate a function in MATLAB. When the argument of normpdf is too small, MATLAB reports a zero. Is is possible to get the exact value of normpdf instead of 0? normpdf MATLAB Answers — New Questions
how to solve the error comes in line 25
clear, clc
format longg
GM = 0.3986004415E+15;
alpha = 0.63781363E+07;
% Load data
%data = importdata(‘EGM08.txt’);
data = readtable(‘EGM08.txt’, ‘ReadVariableNames’, false);
% Extract sigma and beta values
sigma = data(:,5);
beta = data(:,6);
% Initialize Dw
Dw = 0;
% Calculate Dw using the equation
for n = 0:78
summation = 0;
for m = 0:2190
summation = summation + (sigma(m+1)^2 + beta(m+1)^2); % This is the line 25
end
Dw = Dw + sqrt((GM/alpha)^2 * summation);
end
% Display the result
disp([‘Dw = ‘,num2str(Dw)]);
when running the program the following error comes.
Error using egm2008 (line 25)
Subscripting into a table using one
subscript (as in t(i)) is not
supported. Specify a row subscript and
a variable subscript, as in
t(rows,vars). To select variables, use
t(:,i) or for one variable t.(i). To
select rows, use t(i,:).
EGM08.txt have 2401334 rows and 6 columns.clear, clc
format longg
GM = 0.3986004415E+15;
alpha = 0.63781363E+07;
% Load data
%data = importdata(‘EGM08.txt’);
data = readtable(‘EGM08.txt’, ‘ReadVariableNames’, false);
% Extract sigma and beta values
sigma = data(:,5);
beta = data(:,6);
% Initialize Dw
Dw = 0;
% Calculate Dw using the equation
for n = 0:78
summation = 0;
for m = 0:2190
summation = summation + (sigma(m+1)^2 + beta(m+1)^2); % This is the line 25
end
Dw = Dw + sqrt((GM/alpha)^2 * summation);
end
% Display the result
disp([‘Dw = ‘,num2str(Dw)]);
when running the program the following error comes.
Error using egm2008 (line 25)
Subscripting into a table using one
subscript (as in t(i)) is not
supported. Specify a row subscript and
a variable subscript, as in
t(rows,vars). To select variables, use
t(:,i) or for one variable t.(i). To
select rows, use t(i,:).
EGM08.txt have 2401334 rows and 6 columns. clear, clc
format longg
GM = 0.3986004415E+15;
alpha = 0.63781363E+07;
% Load data
%data = importdata(‘EGM08.txt’);
data = readtable(‘EGM08.txt’, ‘ReadVariableNames’, false);
% Extract sigma and beta values
sigma = data(:,5);
beta = data(:,6);
% Initialize Dw
Dw = 0;
% Calculate Dw using the equation
for n = 0:78
summation = 0;
for m = 0:2190
summation = summation + (sigma(m+1)^2 + beta(m+1)^2); % This is the line 25
end
Dw = Dw + sqrt((GM/alpha)^2 * summation);
end
% Display the result
disp([‘Dw = ‘,num2str(Dw)]);
when running the program the following error comes.
Error using egm2008 (line 25)
Subscripting into a table using one
subscript (as in t(i)) is not
supported. Specify a row subscript and
a variable subscript, as in
t(rows,vars). To select variables, use
t(:,i) or for one variable t.(i). To
select rows, use t(i,:).
EGM08.txt have 2401334 rows and 6 columns. error MATLAB Answers — New Questions
What could be the solution of this error (Parse error ar'(‘:usage might be invalid MATLAB syntax)?
I have the following error that is appearing in my work in %time domain
%time domain
1-tmin=0;
2-tmax=200;
3-dt1= ((2*D)/(U^2))-(deltax/U);
4-deltat=0.8*min([0.1,dt1]);
5-if deltat<0.01
6-deltat=0.01;
end
Line 6 deltat = 0.01;
the error is (Parse error ar'(‘:usage might be invalid MATLAB syntax).I have the following error that is appearing in my work in %time domain
%time domain
1-tmin=0;
2-tmax=200;
3-dt1= ((2*D)/(U^2))-(deltax/U);
4-deltat=0.8*min([0.1,dt1]);
5-if deltat<0.01
6-deltat=0.01;
end
Line 6 deltat = 0.01;
the error is (Parse error ar'(‘:usage might be invalid MATLAB syntax). I have the following error that is appearing in my work in %time domain
%time domain
1-tmin=0;
2-tmax=200;
3-dt1= ((2*D)/(U^2))-(deltax/U);
4-deltat=0.8*min([0.1,dt1]);
5-if deltat<0.01
6-deltat=0.01;
end
Line 6 deltat = 0.01;
the error is (Parse error ar'(‘:usage might be invalid MATLAB syntax). parse error, matlab syntax MATLAB Answers — New Questions
Do MBPO agents not support recurrent neural networks for the environment model, the base off-policy agent, or both?
Since TD3, SAC, etc. agents support using recurrent layers by themselves, would using these recurrent base agents still not work with MBPO?
Could this limit be circumvented by using a custom training loop for the environment model and for the base agents?Since TD3, SAC, etc. agents support using recurrent layers by themselves, would using these recurrent base agents still not work with MBPO?
Could this limit be circumvented by using a custom training loop for the environment model and for the base agents? Since TD3, SAC, etc. agents support using recurrent layers by themselves, would using these recurrent base agents still not work with MBPO?
Could this limit be circumvented by using a custom training loop for the environment model and for the base agents? mbpo MATLAB Answers — New Questions
How do you combine multiple sliders into one on Matlab?
I have 3 different sliders doing 3 different things and I’m trying to have all the things being done to it in one function at the same time. I’ve tried many different things and I still don’t know how. If anybody could provide some insight that would be greatly appreciated.
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
conslider = uislider;
conslider.Position = [150 20 300 3];
conslider.Limits = [0 2];
conslider.Value = 1;
conslider.MajorTicks = [0 0.5 1 1.5 2];
conslider.ValueChangedFcn = @updateImage;
function updateImage(conslider,~)
contrastFactor = conslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imadjust(outputImage, [], [], contrastFactor);
% Display the updated image
imshow(outputImage);
title([‘contrastFactor: ‘ num2str(contrastFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
% Developing a slider to adjust the saturation
satslider = uislider;
satslider.Position = [150 20 300 3];
satslider.Limits = [0 2];
satslider.Value = 1;
satslider.MajorTicks = [0 0.5 1 1.5 2];
satslider.ValueChangedFcn = @updateImage
function updateImage(satslider,~)
% Read the current saturation value from the slider
saturationFactor = satslider.Value;
% Convert the image to HSV color space
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
% Update the saturation (S)
hsvImage(:, :, 2) = hsvImage(:, :, 2) * saturationFactor;
% Convert the modified image back to RGB color space
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
% Display the updated image
imshow(outputImage);
title([‘Saturation Factor: ‘ num2str(saturationFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
sharpslider = uislider;
sharpslider.Position = [150 20 300 3];
sharpslider.Limits = [0 2];
sharpslider.Value = 1;
sharpslider.MajorTicks = [0 0.5 1 1.5 2];
sharpslider.ValueChangedFcn = @updateImage;
function updateImage(sharpslider,~)
sharpenFactor = sharpslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imsharpen(inputImage, ‘Amount’, sharpenFactor);
% Display the updated image
imshow(outputImage);
title([‘sharpenFactor: ‘ num2str(sharpenFactor)]);
endI have 3 different sliders doing 3 different things and I’m trying to have all the things being done to it in one function at the same time. I’ve tried many different things and I still don’t know how. If anybody could provide some insight that would be greatly appreciated.
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
conslider = uislider;
conslider.Position = [150 20 300 3];
conslider.Limits = [0 2];
conslider.Value = 1;
conslider.MajorTicks = [0 0.5 1 1.5 2];
conslider.ValueChangedFcn = @updateImage;
function updateImage(conslider,~)
contrastFactor = conslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imadjust(outputImage, [], [], contrastFactor);
% Display the updated image
imshow(outputImage);
title([‘contrastFactor: ‘ num2str(contrastFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
% Developing a slider to adjust the saturation
satslider = uislider;
satslider.Position = [150 20 300 3];
satslider.Limits = [0 2];
satslider.Value = 1;
satslider.MajorTicks = [0 0.5 1 1.5 2];
satslider.ValueChangedFcn = @updateImage
function updateImage(satslider,~)
% Read the current saturation value from the slider
saturationFactor = satslider.Value;
% Convert the image to HSV color space
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
% Update the saturation (S)
hsvImage(:, :, 2) = hsvImage(:, :, 2) * saturationFactor;
% Convert the modified image back to RGB color space
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
% Display the updated image
imshow(outputImage);
title([‘Saturation Factor: ‘ num2str(saturationFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
sharpslider = uislider;
sharpslider.Position = [150 20 300 3];
sharpslider.Limits = [0 2];
sharpslider.Value = 1;
sharpslider.MajorTicks = [0 0.5 1 1.5 2];
sharpslider.ValueChangedFcn = @updateImage;
function updateImage(sharpslider,~)
sharpenFactor = sharpslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imsharpen(inputImage, ‘Amount’, sharpenFactor);
% Display the updated image
imshow(outputImage);
title([‘sharpenFactor: ‘ num2str(sharpenFactor)]);
end I have 3 different sliders doing 3 different things and I’m trying to have all the things being done to it in one function at the same time. I’ve tried many different things and I still don’t know how. If anybody could provide some insight that would be greatly appreciated.
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
conslider = uislider;
conslider.Position = [150 20 300 3];
conslider.Limits = [0 2];
conslider.Value = 1;
conslider.MajorTicks = [0 0.5 1 1.5 2];
conslider.ValueChangedFcn = @updateImage;
function updateImage(conslider,~)
contrastFactor = conslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imadjust(outputImage, [], [], contrastFactor);
% Display the updated image
imshow(outputImage);
title([‘contrastFactor: ‘ num2str(contrastFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
% Developing a slider to adjust the saturation
satslider = uislider;
satslider.Position = [150 20 300 3];
satslider.Limits = [0 2];
satslider.Value = 1;
satslider.MajorTicks = [0 0.5 1 1.5 2];
satslider.ValueChangedFcn = @updateImage
function updateImage(satslider,~)
% Read the current saturation value from the slider
saturationFactor = satslider.Value;
% Convert the image to HSV color space
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
% Update the saturation (S)
hsvImage(:, :, 2) = hsvImage(:, :, 2) * saturationFactor;
% Convert the modified image back to RGB color space
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
% Display the updated image
imshow(outputImage);
title([‘Saturation Factor: ‘ num2str(saturationFactor)]);
end
% Load the Image
inputImage = imread("funny-animals-190-02.jpg");
% Display original image
imshow(inputImage)
title(‘Original Image’)
sharpslider = uislider;
sharpslider.Position = [150 20 300 3];
sharpslider.Limits = [0 2];
sharpslider.Value = 1;
sharpslider.MajorTicks = [0 0.5 1 1.5 2];
sharpslider.ValueChangedFcn = @updateImage;
function updateImage(sharpslider,~)
sharpenFactor = sharpslider.Value;
inputImage = imread("funny-animals-190-02.jpg");
hsvImage = rgb2hsv(inputImage);
outputImage = hsv2rgb(hsvImage);
% Do the stuff for contrast here
outputImage = imsharpen(inputImage, ‘Amount’, sharpenFactor);
% Display the updated image
imshow(outputImage);
title([‘sharpenFactor: ‘ num2str(sharpenFactor)]);
end sliders MATLAB Answers — New Questions
Observations being read as number of columns instead of rows
Before splitting my data into training, validation, and testing, the code worked fine. After the split, trainnet begins reading the observations as the number of columns instead of by the number of rows. I checked the size of the array files and they are the same size the arrays were before I added a data split. I do not understand why trainnet starts reading the arrays differently. Any help would be appreciated.
Error message:
Error using trainnet
Error forming validation data mini-batch.
Error in MainCode6 (line 40)
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts);
Caused by:
Number of observations in predictors (6) and targets (1) must match. Check that the data and network are
consistent.
% Script Number One
all = readtable(excelFile,"Sheet","Nsplit6",’VariableNamingRule’,’preserve’);
train_ratio = 0.8;
val_ratio = 0.1;
test_ratio = 0.1;
num_samples = size(all, 1);
indices = randperm(num_samples);
num_train = floor(train_ratio * num_samples);
num_val = floor(val_ratio * num_samples);
num_test = num_samples – num_train – num_val;
train_indices = indices(1:num_train);
val_indices = indices(num_train+1:num_train+num_val);
test_indices = indices(num_train+num_val+1:end);
train_data = all(train_indices, :);
val_data = all(val_indices, :);
test_data = all(test_indices, :);
X_train = train_data(:, 1:end-1);
Y_train = train_data(:, end);
X_val = val_data(:, 1:end-1);
Y_val = val_data(:, end);
X_test = test_data(:, 1:end-1);
Y_test = test_data(:, end);
stan_x_train = table2array(X_train);
stan_y_train = table2array(Y_train);
stan_x_val = table2array(X_val);
stan_y_val = table2array(Y_val);
stan_x_test = table2array(X_test);
stan_y_test = table2array(Y_test);
%Script number two
inputSize = 6;
hiddenLayerSize1 = 40;
hiddenLayerSize2 = 20;
hiddenLayerSize3 = 10;
outputSize = 1;
layers = [
featureInputLayer(inputSize)
fullyConnectedLayer(hiddenLayerSize1, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(hiddenLayerSize2, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(hiddenLayerSize3, ‘Name’, ‘fc3’)
reluLayer(‘Name’, ‘relu3’)
fullyConnectedLayer(outputSize, ‘Name’, ‘output’)
];
net = dlnetwork(layers);
opts = trainingOptions(‘adam’, …
‘InitialLearnRate’, 0.01, …
‘MaxEpochs’, 200, …
‘MiniBatchSize’, 20, …
‘ValidationData’, {stan_x_val’, stan_y_val’}, …
‘ValidationFrequency’, 20, …
‘Verbose’, true …
);
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts);Before splitting my data into training, validation, and testing, the code worked fine. After the split, trainnet begins reading the observations as the number of columns instead of by the number of rows. I checked the size of the array files and they are the same size the arrays were before I added a data split. I do not understand why trainnet starts reading the arrays differently. Any help would be appreciated.
Error message:
Error using trainnet
Error forming validation data mini-batch.
Error in MainCode6 (line 40)
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts);
Caused by:
Number of observations in predictors (6) and targets (1) must match. Check that the data and network are
consistent.
% Script Number One
all = readtable(excelFile,"Sheet","Nsplit6",’VariableNamingRule’,’preserve’);
train_ratio = 0.8;
val_ratio = 0.1;
test_ratio = 0.1;
num_samples = size(all, 1);
indices = randperm(num_samples);
num_train = floor(train_ratio * num_samples);
num_val = floor(val_ratio * num_samples);
num_test = num_samples – num_train – num_val;
train_indices = indices(1:num_train);
val_indices = indices(num_train+1:num_train+num_val);
test_indices = indices(num_train+num_val+1:end);
train_data = all(train_indices, :);
val_data = all(val_indices, :);
test_data = all(test_indices, :);
X_train = train_data(:, 1:end-1);
Y_train = train_data(:, end);
X_val = val_data(:, 1:end-1);
Y_val = val_data(:, end);
X_test = test_data(:, 1:end-1);
Y_test = test_data(:, end);
stan_x_train = table2array(X_train);
stan_y_train = table2array(Y_train);
stan_x_val = table2array(X_val);
stan_y_val = table2array(Y_val);
stan_x_test = table2array(X_test);
stan_y_test = table2array(Y_test);
%Script number two
inputSize = 6;
hiddenLayerSize1 = 40;
hiddenLayerSize2 = 20;
hiddenLayerSize3 = 10;
outputSize = 1;
layers = [
featureInputLayer(inputSize)
fullyConnectedLayer(hiddenLayerSize1, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(hiddenLayerSize2, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(hiddenLayerSize3, ‘Name’, ‘fc3’)
reluLayer(‘Name’, ‘relu3’)
fullyConnectedLayer(outputSize, ‘Name’, ‘output’)
];
net = dlnetwork(layers);
opts = trainingOptions(‘adam’, …
‘InitialLearnRate’, 0.01, …
‘MaxEpochs’, 200, …
‘MiniBatchSize’, 20, …
‘ValidationData’, {stan_x_val’, stan_y_val’}, …
‘ValidationFrequency’, 20, …
‘Verbose’, true …
);
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts); Before splitting my data into training, validation, and testing, the code worked fine. After the split, trainnet begins reading the observations as the number of columns instead of by the number of rows. I checked the size of the array files and they are the same size the arrays were before I added a data split. I do not understand why trainnet starts reading the arrays differently. Any help would be appreciated.
Error message:
Error using trainnet
Error forming validation data mini-batch.
Error in MainCode6 (line 40)
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts);
Caused by:
Number of observations in predictors (6) and targets (1) must match. Check that the data and network are
consistent.
% Script Number One
all = readtable(excelFile,"Sheet","Nsplit6",’VariableNamingRule’,’preserve’);
train_ratio = 0.8;
val_ratio = 0.1;
test_ratio = 0.1;
num_samples = size(all, 1);
indices = randperm(num_samples);
num_train = floor(train_ratio * num_samples);
num_val = floor(val_ratio * num_samples);
num_test = num_samples – num_train – num_val;
train_indices = indices(1:num_train);
val_indices = indices(num_train+1:num_train+num_val);
test_indices = indices(num_train+num_val+1:end);
train_data = all(train_indices, :);
val_data = all(val_indices, :);
test_data = all(test_indices, :);
X_train = train_data(:, 1:end-1);
Y_train = train_data(:, end);
X_val = val_data(:, 1:end-1);
Y_val = val_data(:, end);
X_test = test_data(:, 1:end-1);
Y_test = test_data(:, end);
stan_x_train = table2array(X_train);
stan_y_train = table2array(Y_train);
stan_x_val = table2array(X_val);
stan_y_val = table2array(Y_val);
stan_x_test = table2array(X_test);
stan_y_test = table2array(Y_test);
%Script number two
inputSize = 6;
hiddenLayerSize1 = 40;
hiddenLayerSize2 = 20;
hiddenLayerSize3 = 10;
outputSize = 1;
layers = [
featureInputLayer(inputSize)
fullyConnectedLayer(hiddenLayerSize1, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(hiddenLayerSize2, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(hiddenLayerSize3, ‘Name’, ‘fc3’)
reluLayer(‘Name’, ‘relu3’)
fullyConnectedLayer(outputSize, ‘Name’, ‘output’)
];
net = dlnetwork(layers);
opts = trainingOptions(‘adam’, …
‘InitialLearnRate’, 0.01, …
‘MaxEpochs’, 200, …
‘MiniBatchSize’, 20, …
‘ValidationData’, {stan_x_val’, stan_y_val’}, …
‘ValidationFrequency’, 20, …
‘Verbose’, true …
);
netTrained = trainnet(stan_x_train, stan_y_train, net, "mse", opts); dlnetwork, observation error, ann MATLAB Answers — New Questions
Need help figuring out why this nested function is not working
function [imgstruct,xyzuvwcrm] = IMGHandle(inputArg1)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
files = inputArg1;
count = 1;
for k = 1:length(files)
%[h,d]=svecread(files(k).name)
varargout = svec2(files(k).name); %Pass files into function to get img struc
% for i = 1:8
% table(:,i) = varargout(:,:,i);
% end
%Adds name of file to struct
xyzuvwcrm(k).name = files(k).name;
for i = 1:8
for x = 1:54
for y = 1:73
xyzuvwcrm(k).data(count,i) = varargout(x,y,i); %Read matrix val to table
count = count +1; %Counting pixels in the image
end
end
count = 1;
end
%Compute the magnitude of u,v,w and insert into column 9 of xyzuvwcrm
for l = 1:size(xyzuvwcrm(k).data,1)
xyzuvwcrm(k).data(l,9) = sqrt(sum((xyzuvwcrm(k).data(l,4:6)).^2));
end
%Creates the Image pixel structure
xyzuvwcrm(k).data = array2table(xyzuvwcrm(k).data,…
‘VariableNames’,["x mm","y mm","z mm","u m/s","v m/s","w m/s",…
"CHC","R Err","Magnitude"]);
imgstruct(k).name = files(k).name;
imgstruct(k).data = varargout ;%(:,:,i)
end
function varargout = svec2(varargin)
msg = nargchk(1,3,nargin); if ~isempty(msg), error(msg), end;
% Defaults:
if nargin < 3
varargin{3} = 8; % default columns value (13/08/01)
if nargin < 2
varargin{2} = 1; % default number of header lins
end
end
% Assign variables
name = varargin{1};
% append an extension if the user neglected to include it
headerlines = 1;
columns = 8;
% this seems like it would cause as many problems as it might fix.
if isempty(strfind(lower(name),’.v3d’))
name = strcat(name,’.v3D’);
end
% Read the header
fid = fopen(name,’r’);
if fid<0
error(‘File not found’);
end
hdr = fgetl(fid);
fclose(fid);
% Parse the header
% i’m terrible at using regex safely,
% so take this with a grain of salt
hdr = lower(hdr);
i = regexp(hdr,’i=(d+)’,’tokens’);
i = str2double(i{1}{1});
j = regexp(hdr,’j=(d+)’,’tokens’);
j = str2double(j{1}{1});
k = regexp(hdr,’k=(d+)’,’tokens’);
k = str2double(k{1}{1});
% read everything using a convenience tool
data = readmatrix(name,’filetype’,’text’, …
‘expectednumvariables’,columns, …
‘numheaderlines’,headerlines);
badind = find(data>9e9);
if ~isempty(badind), data(badind) = 0; warning(sprintf(‘Bad %d points’,length(badind))); end;
% then reshape
% i don’t know which way this is supposed to be oriented
data = reshape(data,i,j,[]);
data = permute(data,[2 1 3]);
if nargout == 1
varargout{1} = data;
elseif nargout == 2
varargout{1} = hdr;
varargout{2} = data;
elseif nargout == 4
varargout{1} = hdr;
varargout{2} = data;
varargout{3} = str2num(i);
varargout{4} = str2num(j);
varargout{5} = str2num(k);
else
warning(‘Wrong number of outputs’) ;
end
end
end
As you can see from the function above IMGHandle is the main function which uses the function svec2 defined within it. I have made sure that all files are within the same folder and this is the current folder. Have restarted matlab to try to update cache etc.
Currently the output I am getting when trying to pass a struct into IMGHandle is the following:
Error using pivdatareadertest>IMGHandle/svec2
File not found
Error in pivdatareadertest>IMGHandle (line 254)
varargout = svec2(files(k).name); %Pass files into function to get img struc
Error in pivdatareadertest (line 55)
[imgstruct,xyzuvwcrm] = IMGHandle(Class4FS20HZ);
Thank you.function [imgstruct,xyzuvwcrm] = IMGHandle(inputArg1)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
files = inputArg1;
count = 1;
for k = 1:length(files)
%[h,d]=svecread(files(k).name)
varargout = svec2(files(k).name); %Pass files into function to get img struc
% for i = 1:8
% table(:,i) = varargout(:,:,i);
% end
%Adds name of file to struct
xyzuvwcrm(k).name = files(k).name;
for i = 1:8
for x = 1:54
for y = 1:73
xyzuvwcrm(k).data(count,i) = varargout(x,y,i); %Read matrix val to table
count = count +1; %Counting pixels in the image
end
end
count = 1;
end
%Compute the magnitude of u,v,w and insert into column 9 of xyzuvwcrm
for l = 1:size(xyzuvwcrm(k).data,1)
xyzuvwcrm(k).data(l,9) = sqrt(sum((xyzuvwcrm(k).data(l,4:6)).^2));
end
%Creates the Image pixel structure
xyzuvwcrm(k).data = array2table(xyzuvwcrm(k).data,…
‘VariableNames’,["x mm","y mm","z mm","u m/s","v m/s","w m/s",…
"CHC","R Err","Magnitude"]);
imgstruct(k).name = files(k).name;
imgstruct(k).data = varargout ;%(:,:,i)
end
function varargout = svec2(varargin)
msg = nargchk(1,3,nargin); if ~isempty(msg), error(msg), end;
% Defaults:
if nargin < 3
varargin{3} = 8; % default columns value (13/08/01)
if nargin < 2
varargin{2} = 1; % default number of header lins
end
end
% Assign variables
name = varargin{1};
% append an extension if the user neglected to include it
headerlines = 1;
columns = 8;
% this seems like it would cause as many problems as it might fix.
if isempty(strfind(lower(name),’.v3d’))
name = strcat(name,’.v3D’);
end
% Read the header
fid = fopen(name,’r’);
if fid<0
error(‘File not found’);
end
hdr = fgetl(fid);
fclose(fid);
% Parse the header
% i’m terrible at using regex safely,
% so take this with a grain of salt
hdr = lower(hdr);
i = regexp(hdr,’i=(d+)’,’tokens’);
i = str2double(i{1}{1});
j = regexp(hdr,’j=(d+)’,’tokens’);
j = str2double(j{1}{1});
k = regexp(hdr,’k=(d+)’,’tokens’);
k = str2double(k{1}{1});
% read everything using a convenience tool
data = readmatrix(name,’filetype’,’text’, …
‘expectednumvariables’,columns, …
‘numheaderlines’,headerlines);
badind = find(data>9e9);
if ~isempty(badind), data(badind) = 0; warning(sprintf(‘Bad %d points’,length(badind))); end;
% then reshape
% i don’t know which way this is supposed to be oriented
data = reshape(data,i,j,[]);
data = permute(data,[2 1 3]);
if nargout == 1
varargout{1} = data;
elseif nargout == 2
varargout{1} = hdr;
varargout{2} = data;
elseif nargout == 4
varargout{1} = hdr;
varargout{2} = data;
varargout{3} = str2num(i);
varargout{4} = str2num(j);
varargout{5} = str2num(k);
else
warning(‘Wrong number of outputs’) ;
end
end
end
As you can see from the function above IMGHandle is the main function which uses the function svec2 defined within it. I have made sure that all files are within the same folder and this is the current folder. Have restarted matlab to try to update cache etc.
Currently the output I am getting when trying to pass a struct into IMGHandle is the following:
Error using pivdatareadertest>IMGHandle/svec2
File not found
Error in pivdatareadertest>IMGHandle (line 254)
varargout = svec2(files(k).name); %Pass files into function to get img struc
Error in pivdatareadertest (line 55)
[imgstruct,xyzuvwcrm] = IMGHandle(Class4FS20HZ);
Thank you. function [imgstruct,xyzuvwcrm] = IMGHandle(inputArg1)
%UNTITLED2 Summary of this function goes here
% Detailed explanation goes here
files = inputArg1;
count = 1;
for k = 1:length(files)
%[h,d]=svecread(files(k).name)
varargout = svec2(files(k).name); %Pass files into function to get img struc
% for i = 1:8
% table(:,i) = varargout(:,:,i);
% end
%Adds name of file to struct
xyzuvwcrm(k).name = files(k).name;
for i = 1:8
for x = 1:54
for y = 1:73
xyzuvwcrm(k).data(count,i) = varargout(x,y,i); %Read matrix val to table
count = count +1; %Counting pixels in the image
end
end
count = 1;
end
%Compute the magnitude of u,v,w and insert into column 9 of xyzuvwcrm
for l = 1:size(xyzuvwcrm(k).data,1)
xyzuvwcrm(k).data(l,9) = sqrt(sum((xyzuvwcrm(k).data(l,4:6)).^2));
end
%Creates the Image pixel structure
xyzuvwcrm(k).data = array2table(xyzuvwcrm(k).data,…
‘VariableNames’,["x mm","y mm","z mm","u m/s","v m/s","w m/s",…
"CHC","R Err","Magnitude"]);
imgstruct(k).name = files(k).name;
imgstruct(k).data = varargout ;%(:,:,i)
end
function varargout = svec2(varargin)
msg = nargchk(1,3,nargin); if ~isempty(msg), error(msg), end;
% Defaults:
if nargin < 3
varargin{3} = 8; % default columns value (13/08/01)
if nargin < 2
varargin{2} = 1; % default number of header lins
end
end
% Assign variables
name = varargin{1};
% append an extension if the user neglected to include it
headerlines = 1;
columns = 8;
% this seems like it would cause as many problems as it might fix.
if isempty(strfind(lower(name),’.v3d’))
name = strcat(name,’.v3D’);
end
% Read the header
fid = fopen(name,’r’);
if fid<0
error(‘File not found’);
end
hdr = fgetl(fid);
fclose(fid);
% Parse the header
% i’m terrible at using regex safely,
% so take this with a grain of salt
hdr = lower(hdr);
i = regexp(hdr,’i=(d+)’,’tokens’);
i = str2double(i{1}{1});
j = regexp(hdr,’j=(d+)’,’tokens’);
j = str2double(j{1}{1});
k = regexp(hdr,’k=(d+)’,’tokens’);
k = str2double(k{1}{1});
% read everything using a convenience tool
data = readmatrix(name,’filetype’,’text’, …
‘expectednumvariables’,columns, …
‘numheaderlines’,headerlines);
badind = find(data>9e9);
if ~isempty(badind), data(badind) = 0; warning(sprintf(‘Bad %d points’,length(badind))); end;
% then reshape
% i don’t know which way this is supposed to be oriented
data = reshape(data,i,j,[]);
data = permute(data,[2 1 3]);
if nargout == 1
varargout{1} = data;
elseif nargout == 2
varargout{1} = hdr;
varargout{2} = data;
elseif nargout == 4
varargout{1} = hdr;
varargout{2} = data;
varargout{3} = str2num(i);
varargout{4} = str2num(j);
varargout{5} = str2num(k);
else
warning(‘Wrong number of outputs’) ;
end
end
end
As you can see from the function above IMGHandle is the main function which uses the function svec2 defined within it. I have made sure that all files are within the same folder and this is the current folder. Have restarted matlab to try to update cache etc.
Currently the output I am getting when trying to pass a struct into IMGHandle is the following:
Error using pivdatareadertest>IMGHandle/svec2
File not found
Error in pivdatareadertest>IMGHandle (line 254)
varargout = svec2(files(k).name); %Pass files into function to get img struc
Error in pivdatareadertest (line 55)
[imgstruct,xyzuvwcrm] = IMGHandle(Class4FS20HZ);
Thank you. functions MATLAB Answers — New Questions
Seeking Help to Optimize MATLAB Function for reducing running time
Dear MATLAB Community,
I hope this message finds you well. I’m currently working on a project that involves optimizing a MATLAB function for improved performance, and I’m reaching out to seek your valuable assistance.
The function is a crucial component of my project. While it serves its purpose, I believe there is room for enhancement in terms of its execution speed. Now it takes more than 1 hours but I want if we can do it in 20-25 min.
I’ve explored various optimization techniques, including vectorization and sparse matrix usage, but I’m still encountering performance bottlenecks.
If you have experience or expertise in optimizing MATLAB functions or tackling similar challenges, I would greatly appreciate any insights, suggestions, or optimizations you could offer.
Your assistance would not only benefit my project but also contribute to the collective knowledge and expertise of the MATLAB community.
Thank you for considering my request, and I look forward to any guidance or assistance you can provid. der1 and der2 are large file more than 5 mb. So I am unable to attach them. each is a cell of {10980*1} and each elemet of 10980*10980. thanks
function J = customJ(der1, der2, smat, DTM)
% %Calculate system matrix
% der1=der1;
% der2=der2;
% smat =smat;
% phi =phi;
% z = z;
load(‘der1.mat’)
load(‘der2.mat’)
load(‘smat.mat’)
load(‘phi.mat’)
load(‘z.mat’)
Ismart =inv(smat);
n = 10980;
% Preallocate memory for derivative matrices
ns = 28;
nd = 28;
%Jmua = zeros(ns * nd, n);
%Jmus = zeros(ns * nd, n);
Jmua = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
Jmus = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
% Calculate full matrices directly
for ii = 1:n
% Display progress
disp([‘column wise: ‘ num2str(round(ii/n*100)) ‘%’])
dm0dmua = -Ismart * (der1{ii} * phi);
dm0dmus = -Ismart * (der2{ii} * phi);
% Calculate Jmua and Jmus directly
temp1 = DTM.’ * dm0dmua;
temp2 = DTM.’ * dm0dmus;
temp3 = z;
Jmua(:,ii) = temp1(:)./temp3(:);
Jmus(:,ii) = temp2(:)./temp3(:);
end
% Concatenate Jmua and Jmus
J = [real([Jmua, Jmus]); imag([Jmua, Jmus])];
endDear MATLAB Community,
I hope this message finds you well. I’m currently working on a project that involves optimizing a MATLAB function for improved performance, and I’m reaching out to seek your valuable assistance.
The function is a crucial component of my project. While it serves its purpose, I believe there is room for enhancement in terms of its execution speed. Now it takes more than 1 hours but I want if we can do it in 20-25 min.
I’ve explored various optimization techniques, including vectorization and sparse matrix usage, but I’m still encountering performance bottlenecks.
If you have experience or expertise in optimizing MATLAB functions or tackling similar challenges, I would greatly appreciate any insights, suggestions, or optimizations you could offer.
Your assistance would not only benefit my project but also contribute to the collective knowledge and expertise of the MATLAB community.
Thank you for considering my request, and I look forward to any guidance or assistance you can provid. der1 and der2 are large file more than 5 mb. So I am unable to attach them. each is a cell of {10980*1} and each elemet of 10980*10980. thanks
function J = customJ(der1, der2, smat, DTM)
% %Calculate system matrix
% der1=der1;
% der2=der2;
% smat =smat;
% phi =phi;
% z = z;
load(‘der1.mat’)
load(‘der2.mat’)
load(‘smat.mat’)
load(‘phi.mat’)
load(‘z.mat’)
Ismart =inv(smat);
n = 10980;
% Preallocate memory for derivative matrices
ns = 28;
nd = 28;
%Jmua = zeros(ns * nd, n);
%Jmus = zeros(ns * nd, n);
Jmua = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
Jmus = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
% Calculate full matrices directly
for ii = 1:n
% Display progress
disp([‘column wise: ‘ num2str(round(ii/n*100)) ‘%’])
dm0dmua = -Ismart * (der1{ii} * phi);
dm0dmus = -Ismart * (der2{ii} * phi);
% Calculate Jmua and Jmus directly
temp1 = DTM.’ * dm0dmua;
temp2 = DTM.’ * dm0dmus;
temp3 = z;
Jmua(:,ii) = temp1(:)./temp3(:);
Jmus(:,ii) = temp2(:)./temp3(:);
end
% Concatenate Jmua and Jmus
J = [real([Jmua, Jmus]); imag([Jmua, Jmus])];
end Dear MATLAB Community,
I hope this message finds you well. I’m currently working on a project that involves optimizing a MATLAB function for improved performance, and I’m reaching out to seek your valuable assistance.
The function is a crucial component of my project. While it serves its purpose, I believe there is room for enhancement in terms of its execution speed. Now it takes more than 1 hours but I want if we can do it in 20-25 min.
I’ve explored various optimization techniques, including vectorization and sparse matrix usage, but I’m still encountering performance bottlenecks.
If you have experience or expertise in optimizing MATLAB functions or tackling similar challenges, I would greatly appreciate any insights, suggestions, or optimizations you could offer.
Your assistance would not only benefit my project but also contribute to the collective knowledge and expertise of the MATLAB community.
Thank you for considering my request, and I look forward to any guidance or assistance you can provid. der1 and der2 are large file more than 5 mb. So I am unable to attach them. each is a cell of {10980*1} and each elemet of 10980*10980. thanks
function J = customJ(der1, der2, smat, DTM)
% %Calculate system matrix
% der1=der1;
% der2=der2;
% smat =smat;
% phi =phi;
% z = z;
load(‘der1.mat’)
load(‘der2.mat’)
load(‘smat.mat’)
load(‘phi.mat’)
load(‘z.mat’)
Ismart =inv(smat);
n = 10980;
% Preallocate memory for derivative matrices
ns = 28;
nd = 28;
%Jmua = zeros(ns * nd, n);
%Jmus = zeros(ns * nd, n);
Jmua = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
Jmus = spalloc(ns * nd, n, 10*ns*nd); % Preallocate sparse matrix
% Calculate full matrices directly
for ii = 1:n
% Display progress
disp([‘column wise: ‘ num2str(round(ii/n*100)) ‘%’])
dm0dmua = -Ismart * (der1{ii} * phi);
dm0dmus = -Ismart * (der2{ii} * phi);
% Calculate Jmua and Jmus directly
temp1 = DTM.’ * dm0dmua;
temp2 = DTM.’ * dm0dmus;
temp3 = z;
Jmua(:,ii) = temp1(:)./temp3(:);
Jmus(:,ii) = temp2(:)./temp3(:);
end
% Concatenate Jmua and Jmus
J = [real([Jmua, Jmus]); imag([Jmua, Jmus])];
end matrix, multiplication, sparse MATLAB Answers — New Questions
How to detect whether a figure is created by uifigure()
I have the following in my startup.m file,
set(groot,’defaultFigureCreateFcn’,@(fig, ~)addToolbarExplorationButtons(fig));
which throws an error when a uifigure is created,
fig = uifigure;
Error using matlab.ui.Figure/set
Functionality not supported with figures created with
the uifigure function.
So, the question becomes, how can I pre-detect whether fig has been created by uifigure() as opposed to figure()? There don’t appear to be separate classes reserved for the two,
>> class(figure)
ans =
‘matlab.ui.Figure’
>> class(uifigure)
ans =
‘matlab.ui.Figure’I have the following in my startup.m file,
set(groot,’defaultFigureCreateFcn’,@(fig, ~)addToolbarExplorationButtons(fig));
which throws an error when a uifigure is created,
fig = uifigure;
Error using matlab.ui.Figure/set
Functionality not supported with figures created with
the uifigure function.
So, the question becomes, how can I pre-detect whether fig has been created by uifigure() as opposed to figure()? There don’t appear to be separate classes reserved for the two,
>> class(figure)
ans =
‘matlab.ui.Figure’
>> class(uifigure)
ans =
‘matlab.ui.Figure’ I have the following in my startup.m file,
set(groot,’defaultFigureCreateFcn’,@(fig, ~)addToolbarExplorationButtons(fig));
which throws an error when a uifigure is created,
fig = uifigure;
Error using matlab.ui.Figure/set
Functionality not supported with figures created with
the uifigure function.
So, the question becomes, how can I pre-detect whether fig has been created by uifigure() as opposed to figure()? There don’t appear to be separate classes reserved for the two,
>> class(figure)
ans =
‘matlab.ui.Figure’
>> class(uifigure)
ans =
‘matlab.ui.Figure’ figure, uifigure, exploration buttons, graphics, app, gui MATLAB Answers — New Questions
How can I generate code from the system I’ve designed in the fuzzy logic designer?
Hello everyone 🙂
I am currently facing a problem to generate the coding from fuzzy logic designer. . I’m using FIS mamdani type-1, after inserted all the data such as input, rules, and output i don’t know how to generate the coding. How can I generate code from this system? Can someone help me?
Thank you in advance.Hello everyone 🙂
I am currently facing a problem to generate the coding from fuzzy logic designer. . I’m using FIS mamdani type-1, after inserted all the data such as input, rules, and output i don’t know how to generate the coding. How can I generate code from this system? Can someone help me?
Thank you in advance. Hello everyone 🙂
I am currently facing a problem to generate the coding from fuzzy logic designer. . I’m using FIS mamdani type-1, after inserted all the data such as input, rules, and output i don’t know how to generate the coding. How can I generate code from this system? Can someone help me?
Thank you in advance. fis, fuzzy logic designer, deffuzzification MATLAB Answers — New Questions
Solving a System of Nonlinear Equations n Times With Different Values
Hi, I am trying to solve a system of nonlinear equations n times, and recording the output values for each time. For simplicity I wrote less complex, random nonlinear equations here rather than what I was working with, but it is the same idea. I have tried a number of things, and this skeleton of code has been the closest, but I cannot get it to return different values for each iteration. I found that I cannot embed a function into a large for loop because of MATLAB syntax, and placing the for loop within the function returns nothing. I believe that fsolve only solves the system of equations for z1(10) and z2(10) and not the first 9 values in the vectors. I can’t find any information on how to change this. Any help would be greatly appreciated.
x0 = [1,1];
m = 10; % same length as z1 below, because I want to output 10 values
c = 0; % counting value
for q=1:m
x = fsolve(@g,x0)
c = c+1;
p(:,c) = x; % records each output value
end
function F = g(x)
z1 = [5 6 7 8 9 10 11 12 13 14];
z2 = [1 2 3 4 5 6 7 8 9 10];
n = length(z1)
for i=1:n
F(1) = x(1).*x(2) – z1(i)
F(2) = x(1) + x(2)./x(1) – z2(i)
end
endHi, I am trying to solve a system of nonlinear equations n times, and recording the output values for each time. For simplicity I wrote less complex, random nonlinear equations here rather than what I was working with, but it is the same idea. I have tried a number of things, and this skeleton of code has been the closest, but I cannot get it to return different values for each iteration. I found that I cannot embed a function into a large for loop because of MATLAB syntax, and placing the for loop within the function returns nothing. I believe that fsolve only solves the system of equations for z1(10) and z2(10) and not the first 9 values in the vectors. I can’t find any information on how to change this. Any help would be greatly appreciated.
x0 = [1,1];
m = 10; % same length as z1 below, because I want to output 10 values
c = 0; % counting value
for q=1:m
x = fsolve(@g,x0)
c = c+1;
p(:,c) = x; % records each output value
end
function F = g(x)
z1 = [5 6 7 8 9 10 11 12 13 14];
z2 = [1 2 3 4 5 6 7 8 9 10];
n = length(z1)
for i=1:n
F(1) = x(1).*x(2) – z1(i)
F(2) = x(1) + x(2)./x(1) – z2(i)
end
end Hi, I am trying to solve a system of nonlinear equations n times, and recording the output values for each time. For simplicity I wrote less complex, random nonlinear equations here rather than what I was working with, but it is the same idea. I have tried a number of things, and this skeleton of code has been the closest, but I cannot get it to return different values for each iteration. I found that I cannot embed a function into a large for loop because of MATLAB syntax, and placing the for loop within the function returns nothing. I believe that fsolve only solves the system of equations for z1(10) and z2(10) and not the first 9 values in the vectors. I can’t find any information on how to change this. Any help would be greatly appreciated.
x0 = [1,1];
m = 10; % same length as z1 below, because I want to output 10 values
c = 0; % counting value
for q=1:m
x = fsolve(@g,x0)
c = c+1;
p(:,c) = x; % records each output value
end
function F = g(x)
z1 = [5 6 7 8 9 10 11 12 13 14];
z2 = [1 2 3 4 5 6 7 8 9 10];
n = length(z1)
for i=1:n
F(1) = x(1).*x(2) – z1(i)
F(2) = x(1) + x(2)./x(1) – z2(i)
end
end nonlinear system, fsolve MATLAB Answers — New Questions
Finding value for each degree from matlab figure
After running the values I obtained from a NACA profile in Matlab along with the txt file, I perform the smoothing process. I am trying to find equivalents at every level for the figure in the appendix. How can I do it
This is the command I run for the figure I obtained:
[Alfa2D, cl2D, ~, ~]= textread(‘Naca LD1408 9R.txt’,’%f %f %f %f’);
N2D = size(Alfa2D,1);
%————————————————————————–
% Fit a Smoothing Spline Model
%————————————————————————–
f = fit(Alfa2D, cl2D,’smoothingspline’,’SmoothingParam’,0.3)
figure(1); plot(f,Alfa2D,cl2D)After running the values I obtained from a NACA profile in Matlab along with the txt file, I perform the smoothing process. I am trying to find equivalents at every level for the figure in the appendix. How can I do it
This is the command I run for the figure I obtained:
[Alfa2D, cl2D, ~, ~]= textread(‘Naca LD1408 9R.txt’,’%f %f %f %f’);
N2D = size(Alfa2D,1);
%————————————————————————–
% Fit a Smoothing Spline Model
%————————————————————————–
f = fit(Alfa2D, cl2D,’smoothingspline’,’SmoothingParam’,0.3)
figure(1); plot(f,Alfa2D,cl2D) After running the values I obtained from a NACA profile in Matlab along with the txt file, I perform the smoothing process. I am trying to find equivalents at every level for the figure in the appendix. How can I do it
This is the command I run for the figure I obtained:
[Alfa2D, cl2D, ~, ~]= textread(‘Naca LD1408 9R.txt’,’%f %f %f %f’);
N2D = size(Alfa2D,1);
%————————————————————————–
% Fit a Smoothing Spline Model
%————————————————————————–
f = fit(Alfa2D, cl2D,’smoothingspline’,’SmoothingParam’,0.3)
figure(1); plot(f,Alfa2D,cl2D) #matlab, #naca MATLAB Answers — New Questions
How to vectorize this nested for loop?
I am finding the cylindrical projection of an image given the camera intrinsic matrix and the distortion coefficients. After finding the warpped coordinates, I need to find the image value for those cooridnates and assign them to an empty warpped image. I would like to vectorize the nested for loop written at the end. I tried with
sub2ind
had series of errors and gave up. Below is the code:
clc; close all; clear;
% Inputs
fileName = ‘checker.jpg’;
% Add grid line
add_grid = 0;
% Focal lengths
fx = 50;
fy = 50;
% Read image
image = (imread(fileName));
% Get image size
[ydim, xdim, bypixs] = size(image);
% Camera intrinsics
K = [fx, 0, xdim/2; 0, fy, ydim/2; 0, 0, 1];
% Distortion coefficients [k1, k2, k3, p1, p2]
DC = [0, 0, 0, 0, 0];
% Get distrotion coefficients
fx = K(1,1);
fy = K(2,2);
k1 = DC(1);
k2 = DC(2);
k3 = DC(3);
p1 = DC(4);
p2 = DC(5);
% Get image size
[ydim, xdim, bypixs] = size(image);
% Initialize an array
imageCylindrical = uint8(zeros(ydim, xdim, bypixs));
% Get the center of image
xc = xdim/2;
yc = ydim/2;
% Create X and Y coordinates grid
[X,Y] = meshgrid(1:xdim, 1:ydim);
% Perform the cylindrical projection
theta = (X – xc) / fx;
h = (Y – yc) / fy;
% Cylindrical coordinates to Cartesian
xcap = sin(theta);
ycap = h;
zcap = cos(theta);
xyz_cap = cat(3, xcap, ycap, zcap);
xyz_cap = reshape(xyz_cap,[],3);
% Normalized coords
xyz_cap_norm = (K * xyz_cap’)’;
xn = xyz_cap_norm(:,1) ./ xyz_cap_norm(:,3);
yn = xyz_cap_norm(:,2) ./ xyz_cap_norm(:,3);
% Radial and tangential distortion
r = xn.^2 + yn.^2;
xd_r = xn .* (1 + k1 * r.^2 + k2 * r.^4 + k3 * r.^6);
yd_r = yn .* (1 + k1 * r.^2 + k2 * r.^4 + k3 * r.^6);
xd_t = 2 * p1 * xn .* yn + p2 * (r.^2 + 2 * xn.^2);
yd_t = p1 * (r.^2 + 2 * yn.^2) + 2 * p2 * xn .* yn;
xd = xd_r + xd_t;
yd = yd_r + yd_t;
% Reshape and clip coordinates
xd = reshape(ceil(xd),[ydim, xdim]);
yd = reshape(ceil(yd),[ydim, xdim]);
mask = xd > 0 & xd <= xdim & yd > 0 & yd <= ydim;
% Get masked coordinates
xd = xd .* mask;
yd = yd .* mask;
% Get projections
for i = 1:ydim
for j = 1:xdim
if yd(i,j) ~= 0 || xd(i,j)~=0
imageCylindrical(i,j,:) = image(yd(i,j), xd(i,j),:);
end
end
endI am finding the cylindrical projection of an image given the camera intrinsic matrix and the distortion coefficients. After finding the warpped coordinates, I need to find the image value for those cooridnates and assign them to an empty warpped image. I would like to vectorize the nested for loop written at the end. I tried with
sub2ind
had series of errors and gave up. Below is the code:
clc; close all; clear;
% Inputs
fileName = ‘checker.jpg’;
% Add grid line
add_grid = 0;
% Focal lengths
fx = 50;
fy = 50;
% Read image
image = (imread(fileName));
% Get image size
[ydim, xdim, bypixs] = size(image);
% Camera intrinsics
K = [fx, 0, xdim/2; 0, fy, ydim/2; 0, 0, 1];
% Distortion coefficients [k1, k2, k3, p1, p2]
DC = [0, 0, 0, 0, 0];
% Get distrotion coefficients
fx = K(1,1);
fy = K(2,2);
k1 = DC(1);
k2 = DC(2);
k3 = DC(3);
p1 = DC(4);
p2 = DC(5);
% Get image size
[ydim, xdim, bypixs] = size(image);
% Initialize an array
imageCylindrical = uint8(zeros(ydim, xdim, bypixs));
% Get the center of image
xc = xdim/2;
yc = ydim/2;
% Create X and Y coordinates grid
[X,Y] = meshgrid(1:xdim, 1:ydim);
% Perform the cylindrical projection
theta = (X – xc) / fx;
h = (Y – yc) / fy;
% Cylindrical coordinates to Cartesian
xcap = sin(theta);
ycap = h;
zcap = cos(theta);
xyz_cap = cat(3, xcap, ycap, zcap);
xyz_cap = reshape(xyz_cap,[],3);
% Normalized coords
xyz_cap_norm = (K * xyz_cap’)’;
xn = xyz_cap_norm(:,1) ./ xyz_cap_norm(:,3);
yn = xyz_cap_norm(:,2) ./ xyz_cap_norm(:,3);
% Radial and tangential distortion
r = xn.^2 + yn.^2;
xd_r = xn .* (1 + k1 * r.^2 + k2 * r.^4 + k3 * r.^6);
yd_r = yn .* (1 + k1 * r.^2 + k2 * r.^4 + k3 * r.^6);
xd_t = 2 * p1 * xn .* yn + p2 * (r.^2 + 2 * xn.^2);
yd_t = p1 * (r.^2 + 2 * yn.^2) + 2 * p2 * xn .* yn;
xd = xd_r + xd_t;
yd = yd_r + yd_t;
% Reshape and clip coordinates
xd = reshape(ceil(xd),[ydim, xdim]);
yd = reshape(ceil(yd),[ydim, xdim]);
mask = xd > 0 & xd <= xdim & yd > 0 & yd <= ydim;
% Get masked coordinates
xd = xd .* mask;
yd = yd .* mask;
% Get projections
for i = 1:ydim
for j = 1:xdim
if yd(i,j) ~= 0 || xd(i,j)~=0
imageCylindrical(i,j,:) = image(yd(i,j), xd(i,j),:);
end
end
end I am finding the cylindrical projection of an image given the camera intrinsic matrix and the distortion coefficients. After finding the warpped coordinates, I need to find the image value for those cooridnates and assign them to an empty warpped image. I would like to vectorize the nested for loop written at the end. I tried with
sub2ind
had series of errors and gave up. Below is the code:
clc; close all; clear;
% Inputs
fileName = ‘checker.jpg’;
% Add grid line
add_grid = 0;
% Focal lengths
fx = 50;
fy = 50;
% Read image
image = (imread(fileName));
% Get image size
[ydim, xdim, bypixs] = size(image);
% Camera intrinsics
K = [fx, 0, xdim/2; 0, fy, ydim/2; 0, 0, 1];
% Distortion coefficients [k1, k2, k3, p1, p2]
DC = [0, 0, 0, 0, 0];
% Get distrotion coefficients
fx = K(1,1);
fy = K(2,2);
k1 = DC(1);
k2 = DC(2);
k3 = DC(3);
p1 = DC(4);
p2 = DC(5);
% Get image size
[ydim, xdim, bypixs] = size(image);
% Initialize an array
imageCylindrical = uint8(zeros(ydim, xdim, bypixs));
% Get the center of image
xc = xdim/2;
yc = ydim/2;
% Create X and Y coordinates grid
[X,Y] = meshgrid(1:xdim, 1:ydim);
% Perform the cylindrical projection
theta = (X – xc) / fx;
h = (Y – yc) / fy;
% Cylindrical coordinates to Cartesian
xcap = sin(theta);
ycap = h;
zcap = cos(theta);
xyz_cap = cat(3, xcap, ycap, zcap);
xyz_cap = reshape(xyz_cap,[],3);
% Normalized coords
xyz_cap_norm = (K * xyz_cap’)’;
xn = xyz_cap_norm(:,1) ./ xyz_cap_norm(:,3);
yn = xyz_cap_norm(:,2) ./ xyz_cap_norm(:,3);
% Radial and tangential distortion
r = xn.^2 + yn.^2;
xd_r = xn .* (1 + k1 * r.^2 + k2 * r.^4 + k3 * r.^6);
yd_r = yn .* (1 + k1 * r.^2 + k2 * r.^4 + k3 * r.^6);
xd_t = 2 * p1 * xn .* yn + p2 * (r.^2 + 2 * xn.^2);
yd_t = p1 * (r.^2 + 2 * yn.^2) + 2 * p2 * xn .* yn;
xd = xd_r + xd_t;
yd = yd_r + yd_t;
% Reshape and clip coordinates
xd = reshape(ceil(xd),[ydim, xdim]);
yd = reshape(ceil(yd),[ydim, xdim]);
mask = xd > 0 & xd <= xdim & yd > 0 & yd <= ydim;
% Get masked coordinates
xd = xd .* mask;
yd = yd .* mask;
% Get projections
for i = 1:ydim
for j = 1:xdim
if yd(i,j) ~= 0 || xd(i,j)~=0
imageCylindrical(i,j,:) = image(yd(i,j), xd(i,j),:);
end
end
end for loop, performance, vectorization MATLAB Answers — New Questions
Are polyshape vertices preserved reliably without floating point errors?
Suppose I have two polyshapes p1 and p2 and I want to do operations on them (intersection, unions) that in theory should preserve some of the vertices of p1 and p2. My question is, can I rely on this to occur without floating point error from the underlying software algorithm?
In the following example, it seems to be true. The union of p1 and p2 is a quadrilateral whos vertices ought to be the union of the vertices of p1 and p2 separately,
load Data
figure; plot([p1,p2]);axis equal
and this is indeed shown to be the case without the need to apply a floating point error tolerance,
Union=union(p1,p2);
all(ismember(p1.Vertices,Union.Vertices,’rows’))
all(ismember(p2.Vertices,Union.Vertices,’rows’))
The same thing appears to be true with intersections:
figure; plot([p2,p3]);axis equal
Intersection=intersect(p2,p3);
nnz(ismember(p3.Vertices,Intersection.Vertices,’rows’))
But there’s no reason this had to be the case, right?Suppose I have two polyshapes p1 and p2 and I want to do operations on them (intersection, unions) that in theory should preserve some of the vertices of p1 and p2. My question is, can I rely on this to occur without floating point error from the underlying software algorithm?
In the following example, it seems to be true. The union of p1 and p2 is a quadrilateral whos vertices ought to be the union of the vertices of p1 and p2 separately,
load Data
figure; plot([p1,p2]);axis equal
and this is indeed shown to be the case without the need to apply a floating point error tolerance,
Union=union(p1,p2);
all(ismember(p1.Vertices,Union.Vertices,’rows’))
all(ismember(p2.Vertices,Union.Vertices,’rows’))
The same thing appears to be true with intersections:
figure; plot([p2,p3]);axis equal
Intersection=intersect(p2,p3);
nnz(ismember(p3.Vertices,Intersection.Vertices,’rows’))
But there’s no reason this had to be the case, right? Suppose I have two polyshapes p1 and p2 and I want to do operations on them (intersection, unions) that in theory should preserve some of the vertices of p1 and p2. My question is, can I rely on this to occur without floating point error from the underlying software algorithm?
In the following example, it seems to be true. The union of p1 and p2 is a quadrilateral whos vertices ought to be the union of the vertices of p1 and p2 separately,
load Data
figure; plot([p1,p2]);axis equal
and this is indeed shown to be the case without the need to apply a floating point error tolerance,
Union=union(p1,p2);
all(ismember(p1.Vertices,Union.Vertices,’rows’))
all(ismember(p2.Vertices,Union.Vertices,’rows’))
The same thing appears to be true with intersections:
figure; plot([p2,p3]);axis equal
Intersection=intersect(p2,p3);
nnz(ismember(p3.Vertices,Intersection.Vertices,’rows’))
But there’s no reason this had to be the case, right? polyshape, vertices, numerical stability, floating point, intersection, union MATLAB Answers — New Questions
Integrate function by for loop
clear
Cs1=4; Cs2=5.6; Cl1=2; Cl2=2.8; ns1=1.5; ns2=-1.5; nl1=1.5; nl2=-1.5;
rho=1.22; A=10; V=44.72; l=20; n=1;Ua=20;
yaw=0:0.5:90;
t=1:1:60;
u=[4.16886273000000 -5.46160601200000 -2.21536928300000 -0.107926889000000 4.17995704900000 2.70294649300000 -3.57644741500000 2.00451722300000 0.881703288000000 4.62541932200000 1.63637915200000 5.73084754400000 0.961007086000000 0.350184264000000 1.37768570200000 -7.64386640500000 1.09384013000000 -3.32210770200000 1.06977546700000 3.77699477800000 -2.80761673400000 -2.51814521100000 -2.56997163700000 -0.434123529000000 -7.33456835300000 3.18164556400000 -2.46259887500000 -2.81705263700000 -6.11824449800000 4.20959983600000 0.958003023000000 1.34911158700000 -3.66536927800000 1.33702769200000 0.951579011000000 4.81211100200000 1.70504507900000 7.08168644200000 3.20839901100000 -0.438521707000000 2.92055007900000 -0.280320940000000 -1.25512163200000 -2.68273256600000 -5.07343734300000 -1.42260189600000 4.56907055100000 3.27623428200000 -1.23514645600000 -2.86948142600000 1.75847520500000 2.79193783800000 -4.18180552400000 -3.14073219500000 -2.43496557500000 -1.28117719800000 4.95079755900000 -3.52809836900000 1.96375591300000 -5.66592848200000]
for i=1:length(yaw)
ms(i)=2*sin(yaw(i)*pi/180)*V/l;
ml(i)=2.5*sin(yaw(i)*pi/180)*V/l;
if yaw(i)<=40
Cs(i)=Cs1*(sin(yaw(i)*pi/180)/sin(30*pi/180))^ns1;
Cl(i)=Cl1*(sin(yaw(i)*pi/180)/sin(30*pi/180))^nl1;
elseif yaw(i)>40
Cs(i)=Cs2*(sin(yaw(i)*pi/180)/sin(30*pi/180))^ns2;
Cl(i)=Cl2*(sin(yaw(i)*pi/180)/sin(30*pi/180))^nl2;
end
S1(i)=0.5*rho*A*(V^2)*Cs(i); % Steady side forces (Uniform along each row)
L1(i)=0.5*rho*A*(V^2)*Cl(i); % Steady lift forces (Uniform along each row)
Msi=ms(i);
Mli=ml(i);
Csi=Cs(i);
Cli=Cl(i);
Yawi=yaw(i*pi/180);
for j=1:length(t)
Tj=t(j);
Uj=u(j);
fun1=@(t1)(((2.*pi.*n.*Msi)^2).*t1.*exp(-2.*pi.*n.*Msi.*t1)).*Uj.*(Tj-t1);
fun2=@(t1)(((2.*pi.*n.*Mli)^2).*t1.*exp(-2.*pi.*n.*Mli.*t1)).*Uj.*(Tj-t1);
S2(i,j)=rho*A*Csi*Ua*(1+(1/(2*Csi))*diff(Csi)*cot(Yawi))*integral(fun1,0,inf); % Unsteady side forces (noniform along each row and column)
L2(i,j)=rho*A*Csi*Ua*(1+(1/(2*Csi))*diff(Csi)*cot(Yawi))*integral(fun2,0,inf); % Unsteady lift forces (noniform along each row and column)
S(i,j)=Sl(i)+S2(i,j); % Total side forces
L(i,j)=S1(i)+S2(i,j); % Total lift forces
j=j+1
end
i=i+1;
end
Dear experts:
The equations I am going to solve are attached as above screenshot and the code is listed.
To summary, the equation is the: Total force(i,j)=Mean force (i)+Unsteady force (i,j (involve intergration over time interval t1)). Hence I will get i*j number of total force result. It is 181*60 (row*column) data.
The mean force componant S1, L1 is uniform value inside each row, which mean that the mean force does not vary along columnn on each row (i); but the mean force componants only has different value between rows.
The calculation of the unsteady force S2,L2 is more complex and the unsteady force is different between each row and column (i,j), and inside each (i,j), the unsteady force is calculated based on the intergration over time interal (0,infinite):S2 (i,j)=(eq…)*integration(fun1(t1), 0 ,inf), L2 (i,j)=(eq…)*integration(fun2(t1), 0 ,inf),
Thereforce, the total force S(i,j)=S1(i)+S2(i,j), L(i,j)=L1(i)+L2(i,j)
The code does not have problem with calculating the mean force (i) S1, L1, but it shows "Array indices must be positive integers or logical values" after I add the for loop (j) to calculate the unsteay force (i,j) S2, L2 which involve integration over time interval t1.
Could our expert help me fix the code?
Kind Regardsclear
Cs1=4; Cs2=5.6; Cl1=2; Cl2=2.8; ns1=1.5; ns2=-1.5; nl1=1.5; nl2=-1.5;
rho=1.22; A=10; V=44.72; l=20; n=1;Ua=20;
yaw=0:0.5:90;
t=1:1:60;
u=[4.16886273000000 -5.46160601200000 -2.21536928300000 -0.107926889000000 4.17995704900000 2.70294649300000 -3.57644741500000 2.00451722300000 0.881703288000000 4.62541932200000 1.63637915200000 5.73084754400000 0.961007086000000 0.350184264000000 1.37768570200000 -7.64386640500000 1.09384013000000 -3.32210770200000 1.06977546700000 3.77699477800000 -2.80761673400000 -2.51814521100000 -2.56997163700000 -0.434123529000000 -7.33456835300000 3.18164556400000 -2.46259887500000 -2.81705263700000 -6.11824449800000 4.20959983600000 0.958003023000000 1.34911158700000 -3.66536927800000 1.33702769200000 0.951579011000000 4.81211100200000 1.70504507900000 7.08168644200000 3.20839901100000 -0.438521707000000 2.92055007900000 -0.280320940000000 -1.25512163200000 -2.68273256600000 -5.07343734300000 -1.42260189600000 4.56907055100000 3.27623428200000 -1.23514645600000 -2.86948142600000 1.75847520500000 2.79193783800000 -4.18180552400000 -3.14073219500000 -2.43496557500000 -1.28117719800000 4.95079755900000 -3.52809836900000 1.96375591300000 -5.66592848200000]
for i=1:length(yaw)
ms(i)=2*sin(yaw(i)*pi/180)*V/l;
ml(i)=2.5*sin(yaw(i)*pi/180)*V/l;
if yaw(i)<=40
Cs(i)=Cs1*(sin(yaw(i)*pi/180)/sin(30*pi/180))^ns1;
Cl(i)=Cl1*(sin(yaw(i)*pi/180)/sin(30*pi/180))^nl1;
elseif yaw(i)>40
Cs(i)=Cs2*(sin(yaw(i)*pi/180)/sin(30*pi/180))^ns2;
Cl(i)=Cl2*(sin(yaw(i)*pi/180)/sin(30*pi/180))^nl2;
end
S1(i)=0.5*rho*A*(V^2)*Cs(i); % Steady side forces (Uniform along each row)
L1(i)=0.5*rho*A*(V^2)*Cl(i); % Steady lift forces (Uniform along each row)
Msi=ms(i);
Mli=ml(i);
Csi=Cs(i);
Cli=Cl(i);
Yawi=yaw(i*pi/180);
for j=1:length(t)
Tj=t(j);
Uj=u(j);
fun1=@(t1)(((2.*pi.*n.*Msi)^2).*t1.*exp(-2.*pi.*n.*Msi.*t1)).*Uj.*(Tj-t1);
fun2=@(t1)(((2.*pi.*n.*Mli)^2).*t1.*exp(-2.*pi.*n.*Mli.*t1)).*Uj.*(Tj-t1);
S2(i,j)=rho*A*Csi*Ua*(1+(1/(2*Csi))*diff(Csi)*cot(Yawi))*integral(fun1,0,inf); % Unsteady side forces (noniform along each row and column)
L2(i,j)=rho*A*Csi*Ua*(1+(1/(2*Csi))*diff(Csi)*cot(Yawi))*integral(fun2,0,inf); % Unsteady lift forces (noniform along each row and column)
S(i,j)=Sl(i)+S2(i,j); % Total side forces
L(i,j)=S1(i)+S2(i,j); % Total lift forces
j=j+1
end
i=i+1;
end
Dear experts:
The equations I am going to solve are attached as above screenshot and the code is listed.
To summary, the equation is the: Total force(i,j)=Mean force (i)+Unsteady force (i,j (involve intergration over time interval t1)). Hence I will get i*j number of total force result. It is 181*60 (row*column) data.
The mean force componant S1, L1 is uniform value inside each row, which mean that the mean force does not vary along columnn on each row (i); but the mean force componants only has different value between rows.
The calculation of the unsteady force S2,L2 is more complex and the unsteady force is different between each row and column (i,j), and inside each (i,j), the unsteady force is calculated based on the intergration over time interal (0,infinite):S2 (i,j)=(eq…)*integration(fun1(t1), 0 ,inf), L2 (i,j)=(eq…)*integration(fun2(t1), 0 ,inf),
Thereforce, the total force S(i,j)=S1(i)+S2(i,j), L(i,j)=L1(i)+L2(i,j)
The code does not have problem with calculating the mean force (i) S1, L1, but it shows "Array indices must be positive integers or logical values" after I add the for loop (j) to calculate the unsteay force (i,j) S2, L2 which involve integration over time interval t1.
Could our expert help me fix the code?
Kind Regards clear
Cs1=4; Cs2=5.6; Cl1=2; Cl2=2.8; ns1=1.5; ns2=-1.5; nl1=1.5; nl2=-1.5;
rho=1.22; A=10; V=44.72; l=20; n=1;Ua=20;
yaw=0:0.5:90;
t=1:1:60;
u=[4.16886273000000 -5.46160601200000 -2.21536928300000 -0.107926889000000 4.17995704900000 2.70294649300000 -3.57644741500000 2.00451722300000 0.881703288000000 4.62541932200000 1.63637915200000 5.73084754400000 0.961007086000000 0.350184264000000 1.37768570200000 -7.64386640500000 1.09384013000000 -3.32210770200000 1.06977546700000 3.77699477800000 -2.80761673400000 -2.51814521100000 -2.56997163700000 -0.434123529000000 -7.33456835300000 3.18164556400000 -2.46259887500000 -2.81705263700000 -6.11824449800000 4.20959983600000 0.958003023000000 1.34911158700000 -3.66536927800000 1.33702769200000 0.951579011000000 4.81211100200000 1.70504507900000 7.08168644200000 3.20839901100000 -0.438521707000000 2.92055007900000 -0.280320940000000 -1.25512163200000 -2.68273256600000 -5.07343734300000 -1.42260189600000 4.56907055100000 3.27623428200000 -1.23514645600000 -2.86948142600000 1.75847520500000 2.79193783800000 -4.18180552400000 -3.14073219500000 -2.43496557500000 -1.28117719800000 4.95079755900000 -3.52809836900000 1.96375591300000 -5.66592848200000]
for i=1:length(yaw)
ms(i)=2*sin(yaw(i)*pi/180)*V/l;
ml(i)=2.5*sin(yaw(i)*pi/180)*V/l;
if yaw(i)<=40
Cs(i)=Cs1*(sin(yaw(i)*pi/180)/sin(30*pi/180))^ns1;
Cl(i)=Cl1*(sin(yaw(i)*pi/180)/sin(30*pi/180))^nl1;
elseif yaw(i)>40
Cs(i)=Cs2*(sin(yaw(i)*pi/180)/sin(30*pi/180))^ns2;
Cl(i)=Cl2*(sin(yaw(i)*pi/180)/sin(30*pi/180))^nl2;
end
S1(i)=0.5*rho*A*(V^2)*Cs(i); % Steady side forces (Uniform along each row)
L1(i)=0.5*rho*A*(V^2)*Cl(i); % Steady lift forces (Uniform along each row)
Msi=ms(i);
Mli=ml(i);
Csi=Cs(i);
Cli=Cl(i);
Yawi=yaw(i*pi/180);
for j=1:length(t)
Tj=t(j);
Uj=u(j);
fun1=@(t1)(((2.*pi.*n.*Msi)^2).*t1.*exp(-2.*pi.*n.*Msi.*t1)).*Uj.*(Tj-t1);
fun2=@(t1)(((2.*pi.*n.*Mli)^2).*t1.*exp(-2.*pi.*n.*Mli.*t1)).*Uj.*(Tj-t1);
S2(i,j)=rho*A*Csi*Ua*(1+(1/(2*Csi))*diff(Csi)*cot(Yawi))*integral(fun1,0,inf); % Unsteady side forces (noniform along each row and column)
L2(i,j)=rho*A*Csi*Ua*(1+(1/(2*Csi))*diff(Csi)*cot(Yawi))*integral(fun2,0,inf); % Unsteady lift forces (noniform along each row and column)
S(i,j)=Sl(i)+S2(i,j); % Total side forces
L(i,j)=S1(i)+S2(i,j); % Total lift forces
j=j+1
end
i=i+1;
end
Dear experts:
The equations I am going to solve are attached as above screenshot and the code is listed.
To summary, the equation is the: Total force(i,j)=Mean force (i)+Unsteady force (i,j (involve intergration over time interval t1)). Hence I will get i*j number of total force result. It is 181*60 (row*column) data.
The mean force componant S1, L1 is uniform value inside each row, which mean that the mean force does not vary along columnn on each row (i); but the mean force componants only has different value between rows.
The calculation of the unsteady force S2,L2 is more complex and the unsteady force is different between each row and column (i,j), and inside each (i,j), the unsteady force is calculated based on the intergration over time interal (0,infinite):S2 (i,j)=(eq…)*integration(fun1(t1), 0 ,inf), L2 (i,j)=(eq…)*integration(fun2(t1), 0 ,inf),
Thereforce, the total force S(i,j)=S1(i)+S2(i,j), L(i,j)=L1(i)+L2(i,j)
The code does not have problem with calculating the mean force (i) S1, L1, but it shows "Array indices must be positive integers or logical values" after I add the for loop (j) to calculate the unsteay force (i,j) S2, L2 which involve integration over time interval t1.
Could our expert help me fix the code?
Kind Regards array indices must be positive integers or logical, integrate function inside for loop MATLAB Answers — New Questions
cell2table not working!
Hello, I am trying to open a cdf file and save it in a table. I have used cell2table to do that but it just give me the table of cells as shown below in output. I need to read the contents of it. I was wondering if I could get somehelp with this. Thanks
cdf file: https://drive.google.com/file/d/1BZHEewbtvkiWdd_EErnWib-WXb7In2wl/view?usp=drive_link
prog:
files=’D:CDF’;
files = dir(‘mvn_*.cdf’);
num_files = length(files);
data= cell(1, num_files);
nam=files.name;
for j = 1:numel(files)
list = fullfile(files(j).folder, files(j).name);
vars = spdfcdfinfo(list).Variables(:,1);
data{j} = cell2table(spdfcdfread(list), ‘VariableNames’, vars);
end
Output:
data = 1×79 table epochtime_mettime_ephemeristime_unixtime_starttime_endtime_deltatime_integeprom_verheadervalidmoderateswp_indmlut_indeff_indatt_indsc_potmagfquat_scquat_msobins_scpos_sc_msobkgdeaddataefluxquality_flagproject_namespacecraft1
21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 int1621600×1 int3221600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 single21600×3 single21600×4 single21600×4 single21600×1 int1621600×3 single2×64×21600 single2×64×21600 single2×64×21600 single2×64×21600 single21600×1 int16’MAVEN”0’Hello, I am trying to open a cdf file and save it in a table. I have used cell2table to do that but it just give me the table of cells as shown below in output. I need to read the contents of it. I was wondering if I could get somehelp with this. Thanks
cdf file: https://drive.google.com/file/d/1BZHEewbtvkiWdd_EErnWib-WXb7In2wl/view?usp=drive_link
prog:
files=’D:CDF’;
files = dir(‘mvn_*.cdf’);
num_files = length(files);
data= cell(1, num_files);
nam=files.name;
for j = 1:numel(files)
list = fullfile(files(j).folder, files(j).name);
vars = spdfcdfinfo(list).Variables(:,1);
data{j} = cell2table(spdfcdfread(list), ‘VariableNames’, vars);
end
Output:
data = 1×79 table epochtime_mettime_ephemeristime_unixtime_starttime_endtime_deltatime_integeprom_verheadervalidmoderateswp_indmlut_indeff_indatt_indsc_potmagfquat_scquat_msobins_scpos_sc_msobkgdeaddataefluxquality_flagproject_namespacecraft1
21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 int1621600×1 int3221600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 single21600×3 single21600×4 single21600×4 single21600×1 int1621600×3 single2×64×21600 single2×64×21600 single2×64×21600 single2×64×21600 single21600×1 int16’MAVEN”0′ Hello, I am trying to open a cdf file and save it in a table. I have used cell2table to do that but it just give me the table of cells as shown below in output. I need to read the contents of it. I was wondering if I could get somehelp with this. Thanks
cdf file: https://drive.google.com/file/d/1BZHEewbtvkiWdd_EErnWib-WXb7In2wl/view?usp=drive_link
prog:
files=’D:CDF’;
files = dir(‘mvn_*.cdf’);
num_files = length(files);
data= cell(1, num_files);
nam=files.name;
for j = 1:numel(files)
list = fullfile(files(j).folder, files(j).name);
vars = spdfcdfinfo(list).Variables(:,1);
data{j} = cell2table(spdfcdfread(list), ‘VariableNames’, vars);
end
Output:
data = 1×79 table epochtime_mettime_ephemeristime_unixtime_starttime_endtime_deltatime_integeprom_verheadervalidmoderateswp_indmlut_indeff_indatt_indsc_potmagfquat_scquat_msobins_scpos_sc_msobkgdeaddataefluxquality_flagproject_namespacecraft1
21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 double21600×1 int1621600×1 int3221600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 int1621600×1 single21600×3 single21600×4 single21600×4 single21600×1 int1621600×3 single2×64×21600 single2×64×21600 single2×64×21600 single2×64×21600 single21600×1 int16’MAVEN”0′ #cell2table #spdfcdf #table MATLAB Answers — New Questions