https://it.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2019-09-17T02:41:54Ztag:it.mathworks.com,2005:Question/4484382019-03-05T19:40:02Z2019-09-17T02:41:54ZEEG data pre-processing script. Everything works fine until i get this: "Error using floatwrite (line 80) Cannot write output file, check permission and space"I get this error but the rest of the code is working well. It stucks just at the final step, when it is saving the dataset. I'm using EEGlab and these plugins: ERPlab, Biosig, Dipfit, Fileio, Fieldtrip and Firlift.
The full error is:
Error using floatwrite (line 80)
Cannot write output file, check permission and space
Error in floatwrite (line 80)
if fid == -1, error('Cannot write output file, check permission and space'); end;
Error in pop_saveset (line 228)
tmpdata = floatwrite( tmpdata, fullfile(EEG.filepath, EEG.data), 'ieee-le');
I checked the free disk space and it's more than 90 GB so I don't think that's the issue. I also checked if there was any restriction I mistakenly set to the directory I want to save the dataset. I use Mac OS 10.8.5 and MATLAB 2014b. I also tried to set several different directories to check if it was a problem related to a directory the script didn't like for some reason.mimmo vosohttps://it.mathworks.com/matlabcentral/profile/authors/13193143-mimmo-vosotag:it.mathworks.com,2005:Question/4799052019-09-11T12:30:16Z2019-09-17T02:41:40ZBoost/Enhance white pixelsHi
How can I enhance or boost the white pixels of the image? Like multiplying them, make them double. Generally, thicker white lines (see attached).Stelios Fanourakishttps://it.mathworks.com/matlabcentral/profile/authors/10865530-stelios-fanourakistag:it.mathworks.com,2005:Question/4807062019-09-17T02:40:13Z2019-09-17T02:40:13ZWhy does jsonencode function does not remove exponents in a structured cell array containing large integer numbers? I would like to save a structured data in a JSON file. There are various structured array elements that has integer number that needs to be represented without any exponents in the notation.
The following is an example commands that formats correctly as per my requirement on command window. But formats with exponent notation after saving to a json file.
Example:
% Command Window
>> clear all
>> format long g
>> university.department.EEE.studentID = {122323259857567}
university =
struct with fields:
department: [1x1 struct]
>> university.department.EEE.studentID
ans =
1x1 cell array
{[122323259857567]}
%When I write it to JSON File the cell array now saves the above studentID with exponents
>>jsonData = jsonencode(university);
saveFileName = [filePath, '/', 'student1.json'];
fileId = fopen(saveFileName, 'w');
if fileId== -1, error('Cannot create JSON file');end
fwrite(fileId, jsonData, 'char');
fclose(fileId);
Kiran Prakashhttps://it.mathworks.com/matlabcentral/profile/authors/13694579-kiran-prakashtag:it.mathworks.com,2005:Question/4807042019-09-17T02:30:58Z2019-09-17T02:30:58ZTrouble labelling objects with semantic segmentation - pixelLabelColorbarFor my work, I am using a semantic segmentation network to look at photos and classify 3 objects: bubbles, water (the background), and a steel tube (where the bubbles come from). I have the following results:
I have been following this example on automated driving for the project:
https://www.mathworks.com/help/vision/examples/semantic-segmentation-using-deep-learning.html
My issue is that I cannot figure out how to implement the pixellabelcolorbar function or cmap variable in the example. I want to label the colors in my photos based on the classification like in the example. Can anyone please help with this?
The matlab live file is attached, relevant code is under "Running the Neural Network on Bubble Images" section. The test image is also attached.
The bubble classification network is here as a link (too large file size to attach): https://drive.google.com/open?id=1smBGJP3T8b47Cae5Wo6V3fvukuzo-76p
Any assistance is greatly appreciatedWilliam Murrayhttps://it.mathworks.com/matlabcentral/profile/authors/5856907-william-murraytag:it.mathworks.com,2005:Question/4807032019-09-17T02:21:52Z2019-09-17T02:21:52ZchangeFilePaths function not working, all files are returned as unresolved pathsI am using a ground truth object to store segmentation labels. I have a folder containing my images, the ground truth object, and the PixelMapLabels folder. I have moved this folder to a new directory and in order to get my matlab code to use the ground truth object in the new directory I need to change its file paths with the changeFilePaths(gTruth, alter_paths) function.
Below is my code:
% Set datapath
datapath = '/scratch/qbi/uqhrile1';
training_datapath = strcat(datapath,'/training_dataset');
% Get training and testing datasets
training_dataset = imageDatastore(strcat(training_datapath,'/images_rgb'));
% Change pixel map label datapath
load(strcat(training_datapath,'/pixel_maps/eye_segmentation_labels.mat'));
old_data_source = 'D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels';
new_data_source = strcat(training_datapath,'/labels');
old_pixellabel_path = 'D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\pixel_maps\PixelLabelData';
new_pixellabel_path = strcat(training_datapath,'/pixel_maps/PixelLabelData');
alter_paths = {[old_data_source new_data_source];[old_pixellabel_path new_pixellabel_path]};
unresolved_paths = changeFilePaths(gTruth,alter_paths)
Here is the output (I won't include all of it because it's a very long list of filenames):
[�Warning: The data source points to one or more image files that cannot be
found. Update the DataSource filenames using <a
href="matlab:doc('changeFilePaths')">changeFilePaths</a> method.]�
[�> In groundTruth>checkImageFilenames (line 1375)
In groundTruth/checkIfSourceExists (line 1123)
In groundTruth.loadobj (line 988)
In segmentation_neural_network (line 21)]�
unresolved_paths =
200x1 string array
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_106520_segmented.tif"
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_107415_segmented.tif"
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_107535_segmented.tif"
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_107590_segmentated.tif"
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_108070_segmented.tif"
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_108415_segmented.tif"
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_109390_segmented.tif"
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_110360_segmented.tif"
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_110380_segmented.tif"
"D:\20190618-f1\images_extracted_from_zebrafish_movies\20190618-f1_10-27-56\training_dataset\labels\frame_111345_segmented.tif"
Etcetera. I know that the issue is not the difference between backslash (\) and slash (/) - the reason why the old pathways use slash and the new pathways use backslash is because I am moving my code and dataset from Windows to Linux.
Can anyone tell me why all of the pathways I am trying to change are coming back as unresolved?Heather Rileyhttps://it.mathworks.com/matlabcentral/profile/authors/16144331-heather-rileytag:it.mathworks.com,2005:Question/4797792019-09-10T19:35:22Z2019-09-17T02:16:53ZHow to add the values of the attached plot in MATLAB to have the summation as a final result?Hello, I have a code and I have plotted the results like the attached figure, I want to add each Y value generated from the code put the whole summation in one dependent..Is there any way?
Thanks Ahmed Saeed Mansourhttps://it.mathworks.com/matlabcentral/profile/authors/7810205-ahmed-saeed-mansourtag:it.mathworks.com,2005:Question/4806512019-09-16T17:59:39Z2019-09-17T02:15:28ZShifting Baselines of Raman SpectraHi,
I have been trying to detrend raman spectra to bring the baseline down and reduce the affects of flouresence on analysis but when I use the code pasted below (with various adjustments based on the data), it definitely does not come out right at all. Trying to get a xlim of 0-800 with wavenumber (col1) on the x axis and intensity (col2, what I need corrected) on the y axis. I am relatively new to the program but if anyone has advice I would greatly appreciate! (also attatched a csv of one of the data sets in case that helps)
t = 0:300;
dailyFluct = gallery('normaldata',size(t),2);
sdata = cumsum(dailyFluct) + 20 + t/100;
mean(sdata)
figure
plot(t,sdata);
legend('Original Data','Location','northwest');
xlabel('Time (days)');
ylabel('Stock Price (dollars)');
detrend_sdata = detrend(sdata);
trend = sdata - detrend_sdata;
mean(detrend_sdata)
hold on
plot(t,trend,':r')
plot(t,detrend_sdata,'m')
plot(t,zeros(size(t)),':k')
legend('Original Data','Trend','Detrended Data',...
'Mean of Detrended Data','Location','northwest')
xlabel('Time (days)');
ylabel('Stock Price (dollars)');Lindsay Moonhttps://it.mathworks.com/matlabcentral/profile/authors/16252647-lindsay-moontag:it.mathworks.com,2005:Question/4807022019-09-17T02:10:40Z2019-09-17T02:10:40ZNTSTOOL - How to get predicted values of "the future"?Hi,
I see a fair number of people asking the same question and sorry for being a newbie in using the ntstool but again, by using a data set to train and test prediction, how can we then predict a few time steps into the future whereby "the future" is the time steps beyond the data set?
ThanksGabriyel Wonghttps://it.mathworks.com/matlabcentral/profile/authors/3879727-gabriyel-wongtag:it.mathworks.com,2005:Question/4530772019-03-28T14:54:17Z2019-09-17T02:04:58ZLogitech G29 with simulinkHi
I have a logitech G29 driving wheel and pedals on PS3 mode and the simulink realtime library block for Logitech G29. Do you have any idea how can I record steering signals?
I keep on getting error though all the modules and drivers are installed in Matlab.HUSAIN KANCHWALAhttps://it.mathworks.com/matlabcentral/profile/authors/12061588-husain-kanchwalatag:it.mathworks.com,2005:Question/4802692019-09-13T13:33:21Z2019-09-17T02:03:46ZHow to ask the user how many file extensions to search forI currently have a script which find files in a folder with a matching string that the user inputs.
I also have code where the user enters the file extensions he wants the script to look for.
ext1 = inputdlg('Please enter file extension #1: **\*. ');
ext2 = inputdlg('Please enter file extension #2: **\*. ');
ext3 = inputdlg('Please enter file extension #3: **\*. ');
fileData = [dir(fullfile(fileLoc,char(ext1))); dir(fullfile(fileLoc,char(ext2))); dir(fullfile(fileLoc,char(ext3)))];
What I want to do instead of ask the user how many different file extensions he wants to look for and then ask for them accordingly.
(e.g. User inputs he wants to search for 5 different file extensions and the script asks for 5)
I'd like to do this instead of just hard-coding in how many file extensions he can search for.
Nommahhttps://it.mathworks.com/matlabcentral/profile/authors/15980723-nommahtag:it.mathworks.com,2005:Question/4807012019-09-17T01:46:16Z2019-09-17T02:00:26ZHOW TO IMPROVE THE ASSIGNMENT OF DATA IN A SPARSE MATRIX?Hi, All,
I want to improve this code, i have to use sparse matrix and store the data from matrix A to RIG(sparse matrix).
RIG=sparse(10000,10000);
A=rand(3,3);
GDL = randi([10 9000],10000,3);
for i=1:10000
P=GDL(i,:);
RIG(P,P)=A;
end
Total Time:0.930 aprox
Thanks for your time! Any reply will be highly appreciated!Jorge Alvarez Ruffranhttps://it.mathworks.com/matlabcentral/profile/authors/10935309-jorge-alvarez-ruffrantag:it.mathworks.com,2005:Question/4803772019-09-14T14:01:53Z2019-09-17T01:57:32ZHow to Imply the Input Array Dimensions to MATLAB CoderAssuming I have a simple function in MATLAB:
function [ mG ] = ProcessImage( mI ) %#codegen
mG = edge(mI, 'Sobel', [], 'both');
end
Now, I want to generate a C code from it.
I also want the C code to work on any 2D Image mI. Yet I don't know the size on compile time. So in C it is solved by sending the dimensions of the array as parameters to the function. Something like:
function [ mG ] = ProcessImage( mI, numRows, numCols ) %#codegen
mG = edge(mI, 'Sobel', [], 'both');
end
Now, my question is, how can I tell MATLAB Coder to understand those parametters are the size of the input image?Royi Avitalhttps://it.mathworks.com/matlabcentral/profile/authors/1599005-royi-avitaltag:it.mathworks.com,2005:Question/4805912019-09-16T11:52:05Z2019-09-17T01:43:50ZError in onCleanup/delete by create a protected model (line 81)After the try to protect an existing reference model, the error massage:
"Dot indexing is not supported for variables of this type."
To be exact the error happens in the onCleanup/delete function in line 81.
How can i modify my modell to prevent this error?Lars Kahrehttps://it.mathworks.com/matlabcentral/profile/authors/8343831-lars-kahretag:it.mathworks.com,2005:Question/4806842019-09-16T21:20:20Z2019-09-17T01:31:42ZHow can I interpolate data with the function ScatteredInterpolant (or else) within the boundaries of the input data only?Hi,
I'm testing interpolation functions to create grid data (Data Terrain Model) from contour lines stored in an xyz file that I imported in the structure contour_grid:
[xi,yi] = meshgrid(Xmin:res:Xmax, Ymin:res:Ymax);
f = scatteredInterpolant(contour_grid.X,contour_grid.Y,contour_grid.Z);
f.Method = 'natural';
zi= f(xi,yi);
My problem is that the ScatteredInterpolant function struggles to output sensible values outside of the contour lines. It makes sense since it does not have enough points to interpolate properly/sensibly. See "lip" below":
I would like to find a way not to output any data outside of the area defined by my outermost contour line or alternatively to automatically crop the grid domain accordingly (keep anything wth x >1.835 x 10^6 for example in that case).
I can't see how the function can be asked to do that. I'm trying to use indices to discard the erroneous data but I cannot formulate it properly.
Can anyone think of a smart way to do that/ has already solved this kind of issue?
Thank you,
NPhttps://it.mathworks.com/matlabcentral/profile/authors/15681215-nptag:it.mathworks.com,2005:Question/4801322019-09-12T17:09:32Z2019-09-17T01:21:04ZProblem with the variable editor and objects, in 2019bHi, I have an object stored in a MAT file. Please find it attached. I open it with 2019a. I double-click it and the Variable editor opens. If I do the same with 2019b (installed today) the property inspector opens instead. Is it a bug?
Regards, thanks
Vittorio CasellaVittorio Casellahttps://it.mathworks.com/matlabcentral/profile/authors/11852-vittorio-casellatag:it.mathworks.com,2005:Question/4807002019-09-17T01:16:28Z2019-09-17T01:16:28ZComputing Streamlines of Systems of 4+ Ordinary Differential EquationsHi All,
I was wondering how I can compute the streamlines of an autonomous system of 4 or more ordinary differential equations. I know that I can use stream2/stream3 or streamlines to acheive this with 2D/3D systems. Essentially, I am interested in the N-D analogue of stream3 that works for N>3. Thanks in advance.
-Freddie
P.S. If you know of a way to compute pathlines but not streamlines, I would also appreicate it if you could let me know. Frederick Papazyanhttps://it.mathworks.com/matlabcentral/profile/authors/10931343-frederick-papazyantag:it.mathworks.com,2005:Question/4805972019-09-16T12:20:04Z2019-09-17T01:09:54ZError using horzcat Dimensions of matrices being concatenated are not consistent.Error using horzcat
Dimensions of matrices being concatenated are not consistent.
Error in tvf_emd (line 51)
y = [fliplr(y(2:2+num_padding-1)) y fliplr(y(end-num_padding:end-1))]; % padding to deal with boundary effect (symmetric)
I get this error whiles runing my code on a sample data of size 231x500. this codes works well on one sample of size 1x500.
Please any help to run the code on my full data. both data are attached. Please the full codes are also attached.
Please I sincerely needs your support urgently on this.Yussif Moro Awelisahhttps://it.mathworks.com/matlabcentral/profile/authors/13640172-yussif-moro-awelisahtag:it.mathworks.com,2005:Question/4806952019-09-16T23:11:18Z2019-09-17T00:59:36ZFind specific date/time from a series of datenumsI have a 7184x72001 double matrix where the first column is a list of serial datenumbers.
I am happy to keep the format this way, but I need to be able to select a specific date/time from this list so that I can extract the data from certain days/times that I am interested in.
So, is it either possible to:
-search from a list of datenums to find a specific date/time that I provide?
-add a column of str data to a matrix of double?
or-convert all of the datenums to date and time?
I have tried the second approach so far:
D=csvread('Tiritiri5280_PSD_1sHammingWindow_50%Overlap_output.csv'); %load in data
t=D(:,1); %extract time column
formatOut='yymmddHHMMSS';
times=datestr(t, formatOut); %convert t column datenums to date and time
rows=(1:length(times)).'; %number of dates and times we have
D_new=[rows D]; %add new column to D
D_new(:,1)=timeslist(:,2); %add times in different format to D
-this works but I now get the datenum in a different format which is also not readable. How do I keep the date time in yymmddhhmmss in a double matrix? Is this possible?
Here,column 1 is the new dates/times that I tried to insert in readable form, and column 2 is serial datenum.
Louise Wilsonhttps://it.mathworks.com/matlabcentral/profile/authors/15959472-louise-wilsontag:it.mathworks.com,2005:Question/4806992019-09-17T00:50:00Z2019-09-17T00:50:00ZHow can I add a diagonal gradient and corresponding colorbar to a plot?This is what I'd like to create with my own data, how can I add that gradient and colorbar to my plotHalle Bergerhttps://it.mathworks.com/matlabcentral/profile/authors/13139656-halle-bergertag:it.mathworks.com,2005:Question/4806972019-09-16T23:51:37Z2019-09-17T00:33:59ZHow can I plot a sin (x^2) functionhere is my code and it works but the figure is obviously not a sin(x^2) function from -pi to pi
syms x;
f=@(x)sin(x.^2);
x=[-pi pi];plot(x,f(x))
gridDrew Levishttps://it.mathworks.com/matlabcentral/profile/authors/16255546-drew-levistag:it.mathworks.com,2005:Question/4806902019-09-16T21:54:23Z2019-09-17T00:30:45ZHow can i get sub matrices with using for loopHello everyone
I have a matrix A as:
A=[1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
2
2
2
2
3
3
3
3
3
4
4
4
4
4
5
5
5
5
5
6
6
6
6
6
7
7
7
7
7
7
7
7
7
7
8
8
8
8
8
8
8
8
8
8
9
9
9
9
9
9
9
9
9
9
10
10
10
10
10
10
10
10
10
10
11
11
11
11
11
11
11
11
11
11
12
12
12
12
12
12
12
12
12
12]
I get unique(A) as 12. And then i want to get new matrices as
for i=1, A(1) as row which is equal to i. And for i=2, A(2) as row which is equal to i.............for i=12 A(12) as rows which is equal to i.
For example:
A(1)=[1
1
1
1
1
1
1
1
1
1]
A(2)=[2
2
2
2
2
2
2
2
2
2]
A(3)=[3
3
3
3
3]
........
A(12)=[12
12
12
12
12
12
12
12
12
12]
How can i do this with using for loop or another way? I want to get new matrices as A(1) to A(12).Mooner Landhttps://it.mathworks.com/matlabcentral/profile/authors/16254851-mooner-landtag:it.mathworks.com,2005:Question/4797442019-09-10T15:59:16Z2019-09-17T00:29:06ZHow to calculate the rate using a given data set?Hey guys,
I need to estimate the reaction rate from given data in excel. To answer this I set up the differential equations and appointed the given data (for the sake of convenience I briefly reduced the data set here). My first thought was that the most simple way to estimate the rate was to use ODE45, but since it doesn't works I assume I made a mistake somewhere.
This was the code I made:
function [dxdt] = data(t)
A = [0.98 0.97 0.95 0.92 0.90]';
B = [0.99 0.97 0.95 0.93 0.90]';
C = [0.01 0.03 0.07 0.11 0.16]';
A_rad = [0.01 0.02 0.02 0.03 0.03]';
B_rad = [0.01 0.02 0.02 0.03 0.03]';
dAdt = -1 .* A - 100 .* B_rad .* A + 1 .* (A_rad).^2;
dBdt = -100 .* A_rad .* B + 1000 .* B_rad .* C;
dCdt = (20000 ((A).^0.5) .* B) ./(100 + 1000 .*(C./A)); %This is the rate I want to estimate
%dBr_radical = 0; Since equal to zero it can be left out
%dH_radical = 0;
[dxdt] = [dAdt; dBdt; dCdt]
And next to call it:
init = [1 1 0 0 0];
tspan = [0 100];
[t,c] = ode45(@data, tspan, init, []);
plot(t,c)
Can someone help me improving my code?
Thanks in advance,
Kind regards,
Danny Danny Helwegenhttps://it.mathworks.com/matlabcentral/profile/authors/14114779-danny-helwegentag:it.mathworks.com,2005:Question/4806632019-09-16T19:24:07Z2019-09-17T00:27:34ZUsing a script to change uicontrol values in a guiI have a code that initializes a GUI, and then take serial data, compares it to excel master files, and then changes the colors of some uipanels in the gui. this is the code, the comments are generally prototyping or holdovers from other codes I incorporated:
delete(instrfind('Port', 'COM3'));
tag = serial('COM3'); %check which port is used
fopen(tag);
MyGUI;
BOX = char(zeros(2,14));
i=1;
c=0;
TrueValueData = 'C:\MasterCodes.xlsx';
[~,~,TrueValMat] = xlsread(TrueValueData); % Creates matrix filled with the correct values,
% indexed by box, which is the first row
% all proceeding rows are the master value
function result(handles)
for i=1:9223372036854775807 %just keeps looping, will probably replace with a push button to kill
if i>10 %first couple reads are filled with unicode nonsense, this skips that stage
readData = fscanf(tag);
if length(readData)>12
BOX(str2num(readData(8)),1:14)= readData(11:24); % these numbers just give us what we want;
% tags come in initially with some gobbledy-gook
end
%
% if(length(readData)>10) %if chip has been read
%
% ReadChips
if strcmp(TrueValMat{2,1}, BOX(1,:))
set(handles.uipanel1, 'BackgroundColor', 'green');
else
set(handles.uipanel1, 'BackgroundColor', 'red');
end
if strcmp(TrueValMat{2,2}, BOX(2,:))
set(handles.uipanel2, 'Backgroundcolor', 'green');
else
set(handles.uipanel2, 'Backgroundcolor', 'red');
end
end
end
end
function uipanel1_Callback(hObject, eventdata, handles)
result;
function uipanel2_Callback(hObject, eventdata, handles)
result;
end
end
The problem is that this doesnt actually do anything, the GUI comes up, but the loop doesn't iterate, and the colors don't change in the GUI. avram alterhttps://it.mathworks.com/matlabcentral/profile/authors/13236963-avram-altertag:it.mathworks.com,2005:Question/4804612019-09-15T13:55:45Z2019-09-17T00:24:08ZFind the problem with my FFT codeHello
I'm using FFT code to compare the amplitudes of two signals, but the answer is different from my idea.
I measured the pressure signal 1000 times a second.
And one is unchanged, the other is increasing.
I divided these two signals by 8 seconds each and PLOT through FFT.
If I find the amplitude with the code below, the value of the unchanging signal is bigger.
But in my opinion, the amplitude of the magnitude of the increasing signal should be bigger den unchanged signal.
Is my code wrong?
thank you for reading :)
Fs = 1000; % Sampling frequency
T = 1/Fs; % Sample time
L = 8000; % Length of signal
t = (0:L-1)*T; % Time vector
x=TL26; %signal
y=table2array(x);
n=4; %% order of Butterworth filter
Wn=[130 150]; % 130 ~ 150Hz signal
Fn=Fs/2; % Nyquist
ftype='bandpass';
[b,a]=butter(n, Wn/Fn, ftype);%%% butter(): ë²„í„°ì›ŒìŠ¤ returns an order 2*n digital bandpass filter if
%%%fbn is a two-element vector
e=filtfilt(b,a,y);
N = length(e);
NFFT = 2^nextpow2(N); % Next power of 2 from length of y
%Y = fft(y,NFFT)/NFFT;
Y = fft(e,NFFT);
Ya = abs(Y)/NFFT; % correctly normalised amplitude
f = Fs/2*linspace(0,1,NFFT/2+1);
% Plot single-sided amplitude spectrum.
figure(99)
plot(f,2*abs(Ya(1:NFFT/2+1)));
title('Single-Sided Amplitude Spectrum of y(t)')
xlabel('Frequency (Hz)')
ylabel('|Y(f)|')dongwoo kimhttps://it.mathworks.com/matlabcentral/profile/authors/15433021-dongwoo-kimtag:it.mathworks.com,2005:Question/4805592019-09-16T07:23:54Z2019-09-17T00:04:51Z'.' is not an internal or external command, nor is it a runnable program or batch filethis below is raw2jpeg.m:
function raw2jpeg(lfp_file)
cd('lfptools') ;
sys_command = ['./lfpsplitter ../' lfp_file];
system(sys_command,'-echo') ;
cd('..') ;
[lfp_folder, lfp_path , ~] = fileparts(lfp_file) ;
lfp_path = [lfp_folder '/' lfp_path] ;
fin = fopen(strcat(lfp_path, '_imageRef0.raw'), 'r') ;
meta = fopen(strcat(lfp_path, '_metadataRef0.txt'), 'r') ;
for i = 1:3
fgets(meta);
end
fgets(meta, 12)
width = fscanf(meta, '%d') ;
fgets(meta) ;
fgets(meta, 12) ;
height = fscanf(meta, '%d') ;
I = fread(fin, width*height, 'uint16=>uint16') ;
im_in = reshape(I, height, width) ;
im_in = im_in' ;
delete([lfp_path '_imageRef0.raw'], [lfp_path '_metadataRef0.txt'], ...
[lfp_path '_privateMetadataRef1.txt'], [lfp_path '_table.txt']) ;
im_in = im_in.*1.5 ;
imwrite(im2uint8(im_in), strcat(lfp_path,'.jpg')) ;
end
The code below is an example for raw2jpeg.m:
raw2jpeg('../input/dataset/raw.lfp'); (just one row)
And the result shows like this:
'.' is not an internal or external command, nor is it a runnable program or batch file
Incorrect use of fgets
The file identifier is invalid. Generate a valid file identifier using fopen (the error exists in line 11 of raw2jpeg.m)Huadong Huhttps://it.mathworks.com/matlabcentral/profile/authors/15291778-huadong-hutag:it.mathworks.com,2005:Question/4804632019-09-15T14:09:55Z2019-09-17T00:04:13ZWhy I cannot get results when I detect multiple labelsafter I train FasterRCNN object detector, and use the detector to detect multiple labels, the results did not shown
I cannot figure out why the results not shown in the table. so that I cannot calculate the average precision.
I showed my code
%%
trainingData = apple
numClasses = 3;
numClassesPlusBackground = numClasses + 1;
%%
inputLayer = imageInputLayer([32 32 3]);
filterSize = [3 3];
numFilters = 32;
middleLayers = [
convolution2dLayer(filterSize, numFilters, 'Padding', 1)
reluLayer()
convolution2dLayer(filterSize, numFilters, 'Padding', 1)
reluLayer()
maxPooling2dLayer(3, 'Stride',2)
];
finalLayers = [
fullyConnectedLayer(4)
reluLayer
fullyConnectedLayer(width(trainingData))
softmaxLayer
classificationLayer
];
layers = [
inputLayer
middleLayers
finalLayers
]
options = trainingOptions('sgdm', ...
'MiniBatchSize', 1, ...
'InitialLearnRate', 1e-3, ...
'MaxEpochs', 10, ...
'VerboseFrequency', 200, ...
'CheckpointPath', tempdir);
detector = trainFasterRCNNObjectDetector(trainingData, layers, ...
'NegativeOverlapRange',[0 0.3], ...
'PositiveOverlapRange',[0.6 1]);
%%
numImages = height(trainingData);
% Run detector on each image in the test set and collect results.
results = table('Size',[numImages 3],...
'VariableTypes',{'cell','cell','cell'},...
'VariableNames',{'Boxes','Scores','Labels'});
for i = 1:numImages
%ds = imageDatastore(trainingData.imageFilename{i});
% Read the image.
I = imread(trainingData.imageFilename{i});
% Run the detector.
[bboxes,scores,labels] = detect(detector, I);
I=insertObjectAnnotation(I, 'rectangle', bboxes, scores);
% Collect the results.
results.Boxes{i,1} = bboxes;
results.Scores{i,1} = scores;
results.Labels{i,1} = labels;
end
results=struct2table(resultsStruct);
expectedResults = trainingData(:, 2:4);
[ap, recall, precision] = evaluateDetectionPrecision(results,expectedResults);
figure
xlabel('unripeRecall')
ylabel('unripePrecision')
plot(recall, precision)
grid ON
title(sprintf('Average Precision = %.2f', ap));
Carla Shawhttps://it.mathworks.com/matlabcentral/profile/authors/13193285-carla-shawtag:it.mathworks.com,2005:Question/3985782018-05-02T08:12:09Z2019-09-17T00:01:40ZEuclidean distance for 3D dataHye, can anybody help me, what is the calculation to calculate euclidean distance for 3D data that has x,y and z value in Matlab? Thank you so much. Really appreciate if somebody can help me.Nurul Atifahhttps://it.mathworks.com/matlabcentral/profile/authors/12362893-nurul-atifahtag:it.mathworks.com,2005:Question/4806982019-09-16T23:59:31Z2019-09-16T23:59:31ZMATLAB Online App Designer help - WARNING: Error in subscription handler java.lang.NullPointerExceptionHey everyone,
Trolled these forums for years without asking a question, but I'm finally properly stuck!
I've been developing an app in App Designer for the past month or two. I've been working across my Mac (latest OSX, MATLAB 2019a) and a Windows (win10, MATLAB Online).
All has been running smoothly until last week when I was working on the Windows machine and was kindly greeted by the following when trying to launch app designer:
Sep 16, 2019 11:46:35 PM com.mathworks.connector.message_service.impl.MessageServiceJSONImpl handlePublishRequest
WARNING: Error in subscription handler
java.lang.NullPointerException
at com.mathworks.ddux.JSBridge$1.handle(JSBridge.java:58)
at com.mathworks.connector.message_service.impl.MessageServiceJSONImpl.handlePublishRequest(MessageServiceJSONImpl.java:29)
at com.mathworks.connector.message_service.impl.AbstractMessageService.handlePublishRequest(AbstractMessageService.java:58)
at com.mathworks.connector.message_service.impl.JniMessageServiceAdaptorImpl.doHandlePublish(JniMessageServiceAdaptorImpl.java:59)
at com.mathworks.connector.message_service.api.JniMessageServiceAdaptor.fromNative(JniMessageServiceAdaptor.java:21)
What then happens is that App designer does launch in the browser, but when I try to open my project app designer doesnt change from the normal home page.
I read some solutions in other forum posts ascociated with a similar error. These are:
Logging out and back in again. Didnt help.
Waiting and trying later as it could be that the servers are down. Didnt help.
Reinstalling Java. Cant do this as its a corporate machine and I dont have admin privelages.
So I'm hoping someone has come across this and might have a solution?Khan Schroder-Turnerhttps://it.mathworks.com/matlabcentral/profile/authors/6469366-khan-schroder-turnertag:it.mathworks.com,2005:Question/4799742019-09-11T19:01:39Z2019-09-16T23:51:22ZData Classification in MatlabWhen you have data that is very clustered as one but of about 3 or 5 class labels, how do you make the dataset a well spread data set so that the classification models can clearly identify the different classes present.
Thank You in AdvanceDARLINGTON ETAJEhttps://it.mathworks.com/matlabcentral/profile/authors/8753940-darlington-etajetag:it.mathworks.com,2005:Question/4806962019-09-16T23:47:36Z2019-09-16T23:47:36ZHow do I plot interpolated grid data and original datapoint set in the same plot?Hi,
After creating a grid data series (Data Terrain Model) from interpolating contour lines, I would like to plot everything on the same layer, but I am not sure if it is possible in matlab. Here is the gist of what I've done:
[xi,yi] = meshgrid(Xmin:res:Xmax, Ymin:res:Ymax);
f = scatteredInterpolant(contour_grid.X,contour_grid.Y,contour_grid.Z);
zi= f(xi,yi)
Xi=[xi(:); contour_grid.X];
Yi=[yi(:); contour_grid.Y];
Zi=[zi(:); contour_grid.Z];
Is there a way to plot Xi, Yi, and Zi? I'd have to turn these arrays back into grids to be able to use mesh(X,Y,Z) but I am struggling to write how to do that.
Has anyone ever had to do that?
Thanks,
NPhttps://it.mathworks.com/matlabcentral/profile/authors/15681215-nptag:it.mathworks.com,2005:Question/4806912019-09-16T22:25:16Z2019-09-16T23:29:44ZFixing code to do bisection properlyI am trying to use the bisection method to find the root of a function on cody. The question is: Write your own code that implements the bisection method to find 1/29, with accuracy to 4 sig figs. This number can be found be finding the root of 1/x- 29 = 0. This is what I have right now, but get the follwoing errors. What can I do to fix this?
function root = mybisect29th(a,b)
es = 0.00005;
f = @(x) (1/x) - 29;
ea = 100;
root = roots([-1 -29]);
oldm = (a+b)/2;
while ea >= es
if sign(f(a)) == sign(f(b))
a = oldm;
else b = oldm;
end
m = (a + b)/2;
oldm = m;
ea = abs((m - oldm)/oldm) * 100;
end
end
David Zubiatehttps://it.mathworks.com/matlabcentral/profile/authors/14572259-david-zubiatetag:it.mathworks.com,2005:Question/4806942019-09-16T23:09:58Z2019-09-16T23:09:58ZInitial centroids for K-means clustering If I have an array (i.e., 5 by 3 matrix) can serve as the initial centroids for kmeans clustering, how can I properly initialize the kmeans algorithm?
(Matlab's kmeans function has more than 600 lines of code and I have no idea how to modify it...)
The purpose of having my own initial centroids rather than have them randomly generated in the kmeans function is to remove the randomness in the outputs.
P.s. Python has the answer to it but I don't know Python.
https://stackoverflow.com/questions/38355153/initial-centroids-for-scikit-learn-kmeans-clustering
Salad Boxhttps://it.mathworks.com/matlabcentral/profile/authors/11434690-salad-boxtag:it.mathworks.com,2005:Question/4806782019-09-16T20:41:37Z2019-09-16T23:00:32ZHow to create an n by n wilkinson matrix using diag How to create an n by n wilkinson bidiagonal matrix Colani Dlaminihttps://it.mathworks.com/matlabcentral/profile/authors/16254227-colani-dlaminitag:it.mathworks.com,2005:Question/4805182019-09-16T00:16:41Z2019-09-16T23:00:12ZFind Common elements between any two columns in each matrixI'm comparing two matrices: 'KeyNeuronMat1', 100x12 and 'KeyNeuronMat2', 100x9. Each row in the matrix represents a neuron # drawn from a 100 total neurons and each column represents a group # computed by different NN so if a neuron gets assigned to that group, it is given a value "1", else "0". For each column in 'KeyNeuronMat1' (sample below), I'd like to identify which neurons (row indicies)
>> keyNeuronMat1(1:10,1:4)
ans =
1 1 1 1
0 0 0 0
0 1 0 0
0 1 1 1
1 0 0 0
0 0 0 0
0 1 0 0
0 1 0 0
0 0 1 1
0 0 1 1
are in common within each of the groups (e.g. column indicies) in 'KeyNeuronMat2' without using a loop.
>> keyNeuronMat2(1:10,5:8)
ans =
1 0 0 0
1 1 1 1
0 1 0 0
0 0 0 0
1 0 0 0
0 0 0 0
0 0 1 0
0 0 0 0
1 0 0 0
0 0 0 0
Is this possible with bsxfun as I've read about this function being used for similar but was not sure.
I've attached my data.
Thanks for any advice. ARhttps://it.mathworks.com/matlabcentral/profile/authors/7097422-artag:it.mathworks.com,2005:Question/4806622019-09-16T19:10:32Z2019-09-16T22:52:36ZWhat is Jacobi methodHow Can i write a program for Jacobi method un MATLABSara Sarahttps://it.mathworks.com/matlabcentral/profile/authors/16252928-sara-saratag:it.mathworks.com,2005:Question/4284442018-11-07T08:21:35Z2019-09-16T22:51:26Zusing improfile in 2D image.I want to make a graph, which has x-axis, y-axis are size of a image and z-axis is intensity of that pixel, from a black-white image. The image is a just gradation dot(darkest at center).
L = size(my_img);
x = [1:L(1)];
y = [1:L(2)];
improfile(my_img, x, y)
I tried upper one. It shows graph from (1,1) to (end,end). And it is not I wanted. I want to get a cone shape graph.
How can I get that??taewoo kimhttps://it.mathworks.com/matlabcentral/profile/authors/14000115-taewoo-kimtag:it.mathworks.com,2005:Question/4806922019-09-16T22:40:08Z2019-09-16T22:40:08ZGraycoprops calculates only 4 Haralick features? I understand that graycoprops claculates 4 GLCM features (correlation, contrast, homogneity and energy) But I do not understand why it doesn't calculate all Haralick features, or are these 4 inclusive of the rest and are sufficient for texture analysis?
Ed Garhttps://it.mathworks.com/matlabcentral/profile/authors/16255164-ed-gartag:it.mathworks.com,2005:Question/4806882019-09-16T21:49:10Z2019-09-16T22:33:00ZWhy does ode45 generate different sized vectors depending on how output is defined?Here is the function I am trying to solve along with the domain and initial condition:
tspan=[0 10];
x0=0;
func=@(t,x) -2*x+t;
If I try to solve the ode with the following format, the vectors are of size 57x1:
[t,x] = ode45(func, tspan, x0);
However, if I try to solve the ode with another format, the vectors are of size 1x15:
sol = ode45(func, tspan, x0);
t=sol.x;
x=sol.y;
The reason I want to know this is because I want the length and number of time steps during the integration. If I had to guess, I would say that it is given with the second format because if I write it like this:
options = odeset('Stats','on');
[t,x] = ode45(func, tspan, x0, options);
the following appears in the command window :
14 successful steps
2 failed attempts
97 function evaluations
This tells me that there are 14 time steps so the size of sol.t is the correct one. Am I missing something?Andres Morfinhttps://it.mathworks.com/matlabcentral/profile/authors/11966353-andres-morfintag:it.mathworks.com,2005:Question/4806712019-09-16T20:00:11Z2019-09-16T22:32:33Zproblem with the name and colors of function barhi i have this 2 vectors:
R=[0.653368446507723 0.679697416448178 0.498095754312123 0.769842809543479 0.548071337734980 0.741418460004374 0.144309508936660 0.746265427699817]
R2=[0.904344447236355 0.690899146493319 0.813308148441499 0.843404154734088 0.741462108425587 0.743992344988688 0.909516353481475 0.798106660693771 0.914039689234528 0.903749068840837 0.905460998596729 0.681770311602557 0.781886210141303 0.802675616361085 0.612994051471877 0.765830161043075 0.535374786223527 0.859204916375148 0.830628655340404 0.791351283447683 0.870604507634522 0.898272536183366 0.764222229874867 0.647746437097374 0.899728115484892 0.742034443459772 0.915234758056906 0.762508436811915]
the xticklabels is
R={'Loudness','FLucStr','Roughness','Sharpness','Leq','Sil','Tonality','Kurtosis'}
and the color is red
the xticklabels of
R2={'Loudness - FLucStr','Loudness - Roughness','Loudness - Sharpness','Loudness - Leq','Loudness - Sil','Loudness - Tonality','Loudness - Kurtosis', 'FLucStr - Roughness','FLucStr - Sharpness','FLucStr - Leq','FLucStr - Sil','FLucStr - Tonality','FLucStr - Kurtosis','Roughness - Sharpness','Roughness - Leq', 'Roughness - Sil','Roughness - Tonality','Roughness - Kurtosis','Sharpness - Leq','Sharpness - Sil','Sharpness - Tonality','Sharpness - Kurtosis','Leq - Sil','Leq - Tonality', 'Leq - Kurtosis','Sil - Tonality','Sil - Kurtosis','Tonality - Kurtosis'}
and the color is blue.
how can i create only 1 bar graphic with R and R2 in an unique graphic in sequence with relave xticklabels and colors???
mohamed gryaahttps://it.mathworks.com/matlabcentral/profile/authors/15308314-mohamed-gryaatag:it.mathworks.com,2005:Question/4806792019-09-16T20:48:48Z2019-09-16T22:29:43ZGet data from channelHello,
I want to run code with the data I get from a channel...How could I do it?
Thanks.wwwhttps://it.mathworks.com/matlabcentral/profile/authors/11241950-wwwtag:it.mathworks.com,2005:Question/4806652019-09-16T19:31:41Z2019-09-16T22:22:27ZUsing the basic templates, I have to customize my graphs twice - once for private and again for public - I'll attach screen captures - your prior instructions didn't work for meHow can I setup charts for private and public that have the same customizations without doing the work twice? Nelson Nelsonhttps://it.mathworks.com/matlabcentral/profile/authors/16251119-nelson-nelsontag:it.mathworks.com,2005:Question/4797782019-09-10T19:22:33Z2019-09-16T22:17:54ZGtk-Message: 16:17:51.771: Failed to load module "canberra-gtk-module"To whom it may concern,
when I run ./matlab on linux UBUNTU 18.4 LTS an error occours
Gtk-Message: 16:17:51.771: Failed to load module "canberra-gtk-module"
How can I solve this problem?
I hop hearing from you,
VictorVictor Carreirahttps://it.mathworks.com/matlabcentral/profile/authors/16191664-victor-carreiratag:it.mathworks.com,2005:Question/4796862019-09-10T09:47:13Z2019-09-16T22:16:56ZLinear interpolation in loopHello, i'm trying to create a script for traveltime curves which will have as an output several plots with 2 best fit lines. To be more specific, assuming that i have a scatter plot with 10 points, i would like to have a first figure with two best fit lines: the first line created from points 1,2 and the second line from points 3 to 10. The second plot will be consisted from points 1,2,3 and the second from points 4 to 10 etc.. In the following code i have the general script which plots only one line. Thanks in advance!
x = 1:10;
y = x + randn(1,10);
scatter(x,y,40,'b')
P = polyfit(x,y,1);
yfit = P(1)*x+P(2);
hold on;
plot(x,yfit,'r-.');Sirius8https://it.mathworks.com/matlabcentral/profile/authors/9515911-sirius8tag:it.mathworks.com,2005:Question/3413502017-05-22T13:04:17Z2019-09-16T22:14:41ZConstraining parameters in Curve Fitting ToolHello,
I want to fit data to an exponential function a-(a-b)*exp(-c*x) using the Curve Fitting Tool but I want to set the limits on the 3 parameters. I want to add something like this:
options.Unknowns = [a,b,c];
options.Lower = [0,0,0];
options.Upper = [1,0.5,10];
I have generated code from the Curve Fitting Tool, so right now I have the function:
function [fitresult, gof] = createFit2(ExpT, ExpNorm_t1)
% Fit: 'untitled fit 1'.
[xData, yData] = prepareCurveData( ExpT, ExpNorm_t1 );
% Set up fittype and options.
ft = fittype( 'a-(a-b)*exp(-c*x)', 'independent', 'x', 'dependent', 'y' );
opts = fitoptions( 'Method', 'NonlinearLeastSquares' );
opts.Display = 'Off';
opts.StartPoint = [0.586235247766206 0.184587387921842 0.13921839531406];
% Fit model to data.
[fitresult, gof] = fit( xData, yData, ft, opts )
% Plot fit with data.
figure( 'Name', 'Exponential Fit to Data' );
h = plot( fitresult, xData, yData);
legend( h, 'Normalized Tether Intensity vs. time', 'Exponential fil to data', 'Location', 'NorthEast');
% Label axes
xlabel Time[s]
ylabel 'Normalized Tether Intensity'
griid on
I just do not know how to specify parameter limits inside the function. Emilie Vejehttps://it.mathworks.com/matlabcentral/profile/authors/10364392-emilie-vejetag:it.mathworks.com,2005:Question/4804772019-09-15T16:29:21Z2019-09-16T22:11:52ZConditioning bivariate gaussian distributionHi,
I have a bivariate normal distribution as follows f(x):
m = 0;
c = [0.5 0.8; 0.8 2.0];
x1 = -4:0.2:4;
x2 = -4:0.2:4;
[X1, X2] = meshgrid(x1,x2);
X = X1(:)';
Y = X2(:)';
fun = @(X, Y) 1/(2*pi*(det(c))^(0.5))* exp(-(0.5)*sum(([X; Y]-m).*(inv(c)*([X; Y]-m))));
i = @(X)integral(@(Y)fun(X,Y),-inf,inf,'ArrayValued',true);
fplot(i)
And this gives output:
I want to find the f(x / y = 1.5)
I have tried to find f(x) and f(y) and then filter out y = 1.5 to get the x values from the distribution. but this method is not working and giving errors as follows:
mu_x = 0;
c = [0.5 0.8; 0.8 2.0];
x1 = -4:0.2:4;
x2 = -4:0.2:4;
[X1,X2] = meshgrid(x1,x2);
X = X1(:)';
Y = X2(:)';
fun = @(X, Y) 1/(2*pi*(det(c))^(0.5))* exp(-(0.5)*sum(([X; Y]-mu_x).*(inv(c)*([X; Y]-mu_x))));
px = @(X)integral(@(Y)fun(X,Y),-inf,inf,'ArrayValued',true);
py = @(Y)integral(@(X)fun(X,Y),-inf,inf,'ArrayValued',true);
%vq1 = interp1(-3:0.2:3,px,-3:0.2:3)
px = px([-3:0.2:3])
p = [px([-3:0.2:3]); py([-3:0.2:3])]
fplot(py)
The error :
Error using vertcat
Dimensions of arrays being concatenated are not consistent.
Error in pg2>@(X,Y)1/(2*pi*(det(c))^(0.5))*exp(-(1/2)*sum(([X;Y]-mu_x).*(inv(c)*([X;Y]-mu_x)))) (line 109)
fun = @(X, Y) 1/(2*pi*(det(c))^(0.5))* exp(-(1/2)*sum(([X; Y]-mu_x).*(inv(c)*([X; Y]-mu_x))));
Error in pg2>@(Y)fun(X,Y) (line 110)
px = @(X)integral(@(Y)fun(X,Y),-inf,inf,'ArrayValued',true);
Error in integralCalc/iterateArrayValued (line 156)
fxj = FUN(t(1)).*w(1);
Error in integralCalc/vadapt (line 130)
[q,errbnd] = iterateArrayValued(u,tinterval,pathlen);
Error in integralCalc (line 103)
[q,errbnd] = vadapt(@minusInfToInfInvTransform,interval);
Error in integral (line 88)
Q = integralCalc(fun,a,b,opstruct);
Error in pg2>@(X)integral(@(Y)fun(X,Y),-inf,inf,'ArrayValued',true) (line 110)
px = @(X)integral(@(Y)fun(X,Y),-inf,inf,'ArrayValued',true);
Error in pg2>dist (line 113)
px = px([-4:0.2:4])
How do i get the values f(x) and f(y) from px and py in range -4:0.2:4 so that i can find f(x / y = 1.5)?Aishwarya Radhakrishnanhttps://it.mathworks.com/matlabcentral/profile/authors/12911762-aishwarya-radhakrishnantag:it.mathworks.com,2005:Question/4806502019-09-16T17:45:37Z2019-09-16T22:09:40Zhow can i set random number generation limit?how can i set the limit for the data collection for New_cp should be the between 0.1 to 0.59?
size=1e6;
a=randn(size,3);
ad1=makedist('Normal',0,1); a1 = cdf(ad1,a(:,1));
pd2 = makedist('Beta',2,5); New_Cp = icdf(pd2,a1);
hist(New_Cp,25)
Dhruvalkumar Patelhttps://it.mathworks.com/matlabcentral/profile/authors/14776563-dhruvalkumar-pateltag:it.mathworks.com,2005:Question/4806572019-09-16T18:46:12Z2019-09-16T21:55:13ZPlease explain the following line of codePlease explain the following line of code:
o(2.*[1:floor(D/2)]-1)=-32
where
o=-30+60*rand(1,D);Adnaanhttps://it.mathworks.com/matlabcentral/profile/authors/15804760-adnaantag:it.mathworks.com,2005:Question/4806892019-09-16T21:53:19Z2019-09-16T21:54:29ZMixed-integer linear programming constraint definition operation not supportedI am trying to code a linear programming optimization problem but defining the constraint is proving a little difficult. The constraint is determined as:
difference of asset and liabilities cashflows is calculated, and
then the cumulative net cashflows are compounded by interest rates (element wise).
each element of the resultant matrix / vector is divided by a constant (53.844) and
constraint is that each element should be less than or equal to 0.05
I have given my code below but the constraint uses the "cumsum" function, which the problem-based approach doesn't entertain. I have also tried an alternative formulation (shown in the end) to avoid use of cumsum but still I did not had any success.
Please can anyone help to correct the code? Also, it would be useful to know how to formulate this problem in the Solver-based approach. It is the code for setting out the constraint that looks difficult to me.
prices = [99.74 91.22 98.71 103.75 97.15];
cashFlows = [4 5 2.5 5 4; 4 5 2.5 5 4; 4 5 2.5 5 4; 4 5 2.5 5 4; 4 5 102.5 5 4;4 5 0 105 104;4 105 0 0 0; 104 0 0 0 0];
obligations = [5 7 7 6 8 7 20 0]';
nt=size(cashFlows,1)
nb=size(cashFlows,2)
Rates = [0.01; 0.015; 0.017;0.019;0.02;0.025;0.027;0.029];
%Number of bonds available
nBonds = [10;100;20;30;5]
ALM = optimproblem;
bonds = optimvar('bonds',nb,'Type','integer','LowerBound',0,'UpperBound',nBonds);
ALM.ObjectiveSense = 'minimize';
ALM.Objective = prices*bonds;
%Define the constraint
ALM.Constraints.Const1 = (cumsum(cashFlows*bonds-obligations,2).*(1+Rates)')/53.844 <=0.05;
showproblem(ALM)
Solution = solve(ALM);
Solution.bonds = round(Solution.bonds);
Solution.bonds
%Alternative formulation of the constraint to avoid use of cumsum
B = triu(ones(8,5));
C=cashFlows*bonds;
D=C.*B;
E=sum(D,1);
ALM.Constraints.Const1 = (E.*(1+Rates)')/53.844 <=0.05;
L Smithhttps://it.mathworks.com/matlabcentral/profile/authors/15981591-l-smithtag:it.mathworks.com,2005:Question/4805082019-09-15T20:51:07Z2019-09-16T21:54:26ZFailed to install the third-party software: VEXnet Serial USB DriverDoes anyone have a solution to the below error? I'm on a Macbook Pro. I have tried to intall and uninstall numerous times with no luck.
Failed to install the third-party software:
VEXnet Serial USB Driver
This is required by:
Simulink Coder Support Package for ARM Cortex-based VEX MicrocontrollerStan Heberthttps://it.mathworks.com/matlabcentral/profile/authors/16236029-stan-heberttag:it.mathworks.com,2005:Question/4806342019-09-16T15:47:20Z2019-09-16T21:51:52ZRearrange a given arrayGiven a vector
V = [ 19 15 11 2 16 3 1 18 14 3 18 19 20 1 13 4 14 3 1 2 16 4 3 1 19 3 20 4 13 1 15 2 18 4 1 20 19 17 3 1 13 20 3 4 17 18 19 20 14 15 11 2]
I would like to rearrange V in this way.
every 10 element I want to collect the elements that are in the same column of A
A= [0 15 11 2 4 0 3 1 13;
14 0 16 0 0 0 0 0 0;
0 0 0 0 8 0 0 0 0;
0 0 18 0 0 0 0 0 0;
0 0 19 0 0 0 0 0 0;
0 0 0 0 0 0 0 0 0];
In this case, we want to collect 11,16,18,19 and also 4,8. Doesn't mind for the others that are just one in the columns, but if we have the same number I want to collect this two number together (see below with 3)
So for example, for the first 10 elements:
19 15 11 2 16 3 1 18 14 3
they will be rearrange as
19 11 16 18 15 2 3 3 1 14
luca ruozihttps://it.mathworks.com/matlabcentral/profile/authors/5908471-luca-ruozi