https://au.mathworks.com/matlabcentral/answers/questions.atomMATLAB Answers — New Questions2017-06-23T05:05:39Ztag:au.mathworks.com,2005:Question/3459392017-06-23T05:05:39Z2017-06-23T05:05:39ZI have a student version but i cant install simscape although I bought it<p>Cannot find library called 'fl_lib'. To use the library, install 'Simscape'</p>shimon cohenhttps://au.mathworks.com/matlabcentral/profile/authors/3507753-shimon-cohentag:au.mathworks.com,2005:Question/3459382017-06-23T04:52:58Z2017-06-23T04:52:58Zexecuting c++ code within matlab<p>i have a matlab function which consists of a call to c++ code present in the same directory. whenever i execute the function i get an error message:
undefined function or variable 'cimgnbmap'.</p>Gargi Srivastavahttps://au.mathworks.com/matlabcentral/profile/authors/3696536-gargi-srivastavatag:au.mathworks.com,2005:Question/3459372017-06-23T04:52:12Z2017-06-23T04:53:08ZThe functions are plotted differently with my expectation, when I used function_handle and fplot.<img src = "/matlabcentral/answers/uploaded_files/81227/untitled.jpg"><p>I have tried to plot a simple function by using "function_handle" and "fplot".</p><p>I assigned the function (y) into a "function_handle" variable, and the input range of function was set as a variable (named to (range)).</p><p>I thought that the variable (x)'s range will be set from a to b as continuous values, if it was set "range=[a b]".</p><p>i.e., the output (y(u)) should be plotted according to continuous input variable ranged from a to b.</p><p>However, the function was plotted differently with my prediction.</p><p>In my opinion, the upper line had to be nonexistent from the attached plot figure.</p><p>If it is correct what I was predicting, can you suggest any solution or other methods??</p><pre class="language-matlab">y = @(u)(3-u)*[2,2]+(u-2)*[3,0];
range = [2 3];
fplot(@(u) y(u), range, 'color', rand(1,3));
</pre>Sang-Il Ohhttps://au.mathworks.com/matlabcentral/profile/authors/8744316-sang-il-ohtag:au.mathworks.com,2005:Question/3456362017-06-21T09:12:34Z2017-06-23T04:44:11Zsinusoidal time dependent boundary condition - pde toolbox<p>hello,</p><p>i would like to have a sinusoidal time dependent BC.
i didnt find an example of this in the related docs.</p><p>this is the relevant part of the code</p><pre class="language-matlab">tlist=0:30:360;
Flux= @(region,state) sin(2*pi*state.time)*F
b=applyBoundaryCondition(model,'neumann','Face',1,'q',0,'g',Flux,'Vectorized','on');
</pre><p>i want the bc to osicllate with time period of 30. is this the correct way of doing this?</p><p>thank you.</p>yonatan shttps://au.mathworks.com/matlabcentral/profile/authors/9554412-yonatan-stag:au.mathworks.com,2005:Question/3454342017-06-20T04:02:41Z2017-06-23T04:38:12ZExtract X number of elements in 3D matrix based on another matrix<p>Hello,</p><p>I have a 3D Matrix A (3x3x5) that is sorted in descending order and another Matrix B (3x3) which has the first X number of elements in Matrix A that I would like to extract and store in a blank matrix C (3x3x5). Matrix B has different first elements to extract, so I would like the rest of the elements in the 3D matrix C to be zero if there isn't anything copied from A. Let's say there are 2 values that I want to extract at element 1x1x1:5, then cell 1x1x1:2 in Matrix C will be 10; 5; 0; 0;0</p><p>Example of Matrix A and B:
A=randi(10,3,3,5);
B=[NaN 2 1; 2 NaN 2;NaN 4 3];</p><p>Thank you for the help.</p>Vesphttps://au.mathworks.com/matlabcentral/profile/authors/8406199-vesptag:au.mathworks.com,2005:Question/3459332017-06-23T02:23:31Z2017-06-23T04:21:16ZHow to store the looping plot value in to a variable ?<p>Hello</p><p>I have matlab code as follows:
How to store the looping plot value of "ColorPink" over bandnumber into one variable, so I can analyze and cluster this variable for further processing. thanks before</p><pre> for y=1:sample_nu
for x=1:band
Pinkcolor(y,:)=impixel(Color61(:,:,x),PinkColorsampling(y,1),PinkColorsampling(y,2));
ColorPink(x,:)=Pinkcolor(y,:);
end
plot(bandnumber,ColorPink(:,1),'r');hold on
end</pre>lina septianahttps://au.mathworks.com/matlabcentral/profile/authors/8828914-lina-septianatag:au.mathworks.com,2005:Question/3459362017-06-23T03:52:19Z2017-06-23T04:09:49ZI want to save variables to a mat file by reading variable names present in another mat file<p>I have a mat file called names.mat. It has variables say var1="loop_no", var2="phase", var3="flow". These variables are already present in the base workspace. now i want to use this mat file to save similarly names variables in another mat file. i.e instead of writing variable names in the command <b>save(filename,"var1","var2","var3")</b> I want to be able to write the mat file names.mat somewhere in the command so that these variables are automatically saved in the file results.mat. Is it possible?</p>Sadiahttps://au.mathworks.com/matlabcentral/profile/authors/4453857-sadiatag:au.mathworks.com,2005:Question/3459352017-06-23T03:34:50Z2017-06-23T03:34:50ZPromblem in GUI Error while evaluating DestroyedObject Callback<p>Error in
matlab.graphics.internal.figfile.FigFile/read>@(hObject,eventdata)webcam1('exit_Callback',hObject,eventdata,guidata(hObject)) <b>Error using imaqdevice/getdata (line 141)</b> <b>Error while evaluating DestroyedObject Callback</b></p><p><b>Error using matlab.ui.control.UIControl/set
Invalid or deleted object.</b> when press Exit</p><img src = "/matlabcentral/answers/uploaded_files/81226/2017-06-22_134312.png">Adisorn Phanukthonghttps://au.mathworks.com/matlabcentral/profile/authors/6937939-adisorn-phanukthongtag:au.mathworks.com,2005:Question/3457912017-06-22T07:49:11Z2017-06-23T03:32:04ZS-function builderから見えるようにインクルードパスおよびライブラリパスを設定する方法<p>S-function builderから見えるようにインクルードパスおよびライブラリパスを設定するには、
どのように行えばよいのでしょうか。</p><p><a href = "https://jp.mathworks.com/matlabcentral/newsreader/view_thread/88721">https://jp.mathworks.com/matlabcentral/newsreader/view_thread/88721</a></p><p>この質問が丁度同じ内容なのですが、
この質問への回答に相当する内容は、
MATLAB 2016bでも有効でしょうか。</p><p>もしくは別の方法がありましたら教えて下さい。</p>tnksralhttps://au.mathworks.com/matlabcentral/profile/authors/10415639-tnksraltag:au.mathworks.com,2005:Question/3459122017-06-22T22:05:18Z2017-06-23T03:18:44ZHow to only grab *.xls files, not *.xlsx or *.xlsm?<p>I am using the following before I run a loop and it is pulling *.xlsm files. Is there a way to cut off the call at *.xls?</p><pre class="language-matlab">SVMS_xls=dir('*.xls');
</pre>Calabresehttps://au.mathworks.com/matlabcentral/profile/authors/6198613-calabresetag:au.mathworks.com,2005:Question/3459282017-06-23T01:59:56Z2017-06-23T03:17:09ZAssignment has more non-singleton rhs dimensions than non-singleton subscripts<p>hi I keep getting the error which i mentioned in the question.This is a part of the code in which there is an error, if someone could help me out that would be great.
G is a constant defined as 1.2, p_0 is a constant defined as 125000, c is a counter which goes from 1 to 10, n is your max count which is 10.rho is another constant defined as 1.023 and p_0 is defined as 1.225.</p><pre class="language-matlab">pressure = zeros(n,1);
pressure(c,:) = p_0;
p = (rho/rho_0).^G .*p_0;
pressure(c,:) = p;
</pre><pre> end</pre>Manil Athapattuhttps://au.mathworks.com/matlabcentral/profile/authors/7703085-manil-athapattutag:au.mathworks.com,2005:Question/3458972017-06-22T20:03:11Z2017-06-23T03:16:03ZRectangular grid using MATLAB<p>I have two cell arrays and each cell has a matrix x = (10X5). Each row in x is an array (between -1 and 1) with a mean "m" and std "s". Now i want to represent this matrix in a rectangular grid using MATLAB such that each box has a mean (orange color) and std deviation (filled with red colour in either side of mean) as shown in the example. So basically there should be 10X2 rectangular grids (corresponding to 10 rows and two cells). Can someone please help me with this? I looked up online but could not find anything.</p><img src = "/matlabcentral/answers/uploaded_files/81203/VR4an.jpg">Sowmya MRhttps://au.mathworks.com/matlabcentral/profile/authors/6380289-sowmya-mrtag:au.mathworks.com,2005:Question/3459342017-06-23T02:34:01Z2017-06-23T03:12:07ZHow can fix the error 'Invalid calling syntax for the "predict" command.' when using the predict function?<p>I used fitcsvm to train INRIAPerson and when I was using the predict function to get the label of input images, I got an error which is 'Invalid calling syntax for the "predict" command'. But it worked in another code. It confused me and I really do not know how to fix it.
Here is how I train the classifier:</p><pre> function TrainingSVM()
%Input the training images and set image size.
imgTrain = imageDatastore('D:\TrainImage\INRIAPerson','IncludeSubfolders', true, 'LabelSource', 'foldernames');
imageSize = [96, 48];
Test = readimage(imgTrain,1);
Test = imresize(Test,imageSize);
[features, ~] = extractHOGFeatures(Test);
numImages = length(imgTrain.Files);
data = zeros(numImages,size(features,2),'single');
for i = 1:numImages
Train = readimage(imgTrain,i);
Train = imresize(Train,imageSize);
data(i,:) = extractHOGFeatures(Train);
end
trainLabels = imgTrain.Labels;
classifier = fitcsvm(data,trainLabels);
save classifier
end</pre><p>Here is the error code.</p><pre> function PedestrianTracking()</pre><pre> %Load the pre-trained classifier
classifier = 'classifier.mat';</pre><pre> %Create object obj
obj = setupSystemObjects(); </pre><pre> % Detect moving objects, and track them across video frames.
while ~isDone(obj.reader)
Frame = readFrame();
frame = imresize(Frame, 0.5, 'Antialiasing',false);
[centroids, bboxes, ~] = detectObjects(frame);
Size = size(bboxes);
%Find areas contain people and save them.
Bboxes = [];
Centroids = [];
for i = 1:Size(1,1)
%Get the target area
detectImage = imcrop(frame, bboxes(i, :));
%Resize the target area and do the classification with classifier
DetectImage = imresize(detectImage, [96, 48]);
feature = extractHOGFeatures(DetectImage);
[predictIndex,~] = predict(classifier,feature);
% If people are detected in the DetectImage then store it.
if ( char(predictIndex) - 48 ) == 1
Bboxes = [Bboxes; bboxes(i, :)];
Centroids = [Centroids, centroids(i, :)]
end
end
end</pre><pre> function [centroids, bboxes, mask] = detectObjects(frame)
% Detect foreground.
mask = obj.detector.step(frame);
% Apply morphological operations to remove noise and fill in holes.
mask = imopen(mask, strel('rectangle', [3,3]));
mask = imclose(mask, strel('rectangle', [15, 15]));
mask = imfill(mask, 'holes');
% Perform blob analysis to find connected components.
[~, centroids, bboxes] = obj.blobAnalyser.step(mask);
end</pre><pre> function obj = setupSystemObjects()
obj.reader = vision.VideoFileReader('D:D:\TestVideo\1.mp4');
obj.detector = vision.ForegroundDetector('NumGaussians', 4, ...
'NumTrainingFrames', 20, 'MinimumBackgroundRatio', 0.7);
obj.blobAnalyser = vision.BlobAnalysis('BoundingBoxOutputPort', true, ...
'AreaOutputPort', true, 'CentroidOutputPort', true, ...
'MinimumBlobArea', 4000);
obj.videoPlayer = vision.VideoPlayer('Position', [20, 400, 700, 400]);
end</pre><pre> end</pre>BOFU LIUhttps://au.mathworks.com/matlabcentral/profile/authors/9535690-bofu-liutag:au.mathworks.com,2005:Question/3459322017-06-23T02:15:11Z2017-06-23T03:00:38ZHow to efficiently create a vector?<p>I want create a matrix such that</p><p>A matrix mat_B = [ 1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15; 16 17 18 19 20].</p><p>Is there any other code that more efficient than the code I make below?</p><p>for i = 1:5
if i ==1
a (i,:)=1:4;
else
a (i,:) = (a (i-1,:))+4;
end
end</p>balandonghttps://au.mathworks.com/matlabcentral/profile/authors/3080660-balandongtag:au.mathworks.com,2005:Question/3307122017-03-19T19:28:34Z2017-06-23T03:00:03ZMean Js stack and Matlab<p>I am currently developing a website with mean js stack for fingerprint recognition , the implementation of the method of recognition is in Matlab so is there any way to link Matlab production server with mean js ?</p>ketima buhttps://au.mathworks.com/matlabcentral/profile/authors/9570744-ketima-butag:au.mathworks.com,2005:Question/3457702017-06-22T04:56:29Z2017-06-23T02:46:50Zhow to use Slider Switch in simulink model ?<p>How to use Slider Switch in simulink model ?
Help document write a little bit.</p>jingwie sunhttps://au.mathworks.com/matlabcentral/profile/authors/10258136-jingwie-suntag:au.mathworks.com,2005:Question/1791292015-02-18T18:41:46Z2017-06-23T02:40:07ZIs it possible to rename columns in a table?<p>Hi,</p><p>I'm hoping there's a simple way to rename columns in a table. I don't need anything complicated, I'd just like to rename, for example, the 2nd, 7th, and 16th columns of a table - inside a function.</p><p>Thanks!</p>Chelseahttps://au.mathworks.com/matlabcentral/profile/authors/5522099-chelseatag:au.mathworks.com,2005:Question/3459302017-06-23T02:09:44Z2017-06-23T02:36:17Zif the number of samples for doing fft is not n power of 2 the results accuracy would be affected?<p>Hi everyone!
I haved been reading that matlab can perform fft when the length of the signal is not n power of 2 but I want to know if that would affect the accuracy of the results.
Thanks in advance!</p>Alehttps://au.mathworks.com/matlabcentral/profile/authors/5765484-aletag:au.mathworks.com,2005:Question/3459312017-06-23T02:14:01Z2017-06-23T02:15:49Zimplement adaptive watershed algorithm<p>I was trying to implement adaptive watershed mentioned in "Adaptive watershed segmentation of binary particle image by H.Q. SUN & Y.J. LUO". I'm a newbie in image processing. I tried some code but I don't know its correct or not. I tried to implement the last step.</p><pre class="language-matlab">close all
%% Load image
input_image = imread('input.gif');
figure
imshow(input_image)
bw = im2bw(input_image);
%% Step 1 :Calculate Euclidean distance
D = bwdist(bw,'euclidean'); %Euclidean distance
[m,n]=size(D);
M = zeros(m,n);
</pre><pre class="language-matlab">%% Step 2 : Smooth the distance map using Gaussian filter to merge the adjacentmaxima
H = fspecial('gaussian');
g = imfilter(D,H);
M = imregionalmax(g); % maker map,
</pre><pre class="language-matlab">%Step3 :Scan the marker map pixel by pixel set M
for x0 = 1:m
for y0 = 1:n
if M(x0,y0) == 1
r = ceil(g(x0,y0));
% range begin:(x0-r,y0-r) end:(x0+r,y0+r)
xb = x0-r;
if xb <= 0
xb =1;
end
</pre><pre> yb = y0-r;
if yb <= 0
yb =1;
end</pre><pre> xe = x0+r;
if xe > m
xe = m;
end</pre><pre> ye = y0+r;
if ye > n
ye = n;
end</pre><pre> for x = xb:xe
for y = yb:ye
if M(x,y)==1
Pos = [x0,y0 ;x,y];
Dis = pdist(Pos,'euclidean');
IFA = Dis<= (g(x0,y0));
IFB = g(x,y)<g(x0,y0);
if ( IFA && IFB)
M(x,y) = 0;
end
end
end
end
end
end
end</pre><pre class="language-matlab">%% Step 4
igfDT = imcomplement(g);
</pre><pre class="language-matlab">%% STep 5
I2 = imimposemin(igfDT, M);
L = watershed(I2);
igfDT(L==0)=1;
% % % skel = bwmorph(L,'thicken', Inf); % skeletonization for finding minitues
% % % rem = bwareaopen(~skel, 100);
% % % skel = ~rem;
% % % figure
% % % imshow(skel)
% % % title('Skeleton')
% % % %% delete small segments (imgprops)
% % % stats = regionprops(~skel,'Area', 'PixelIdxList');
% % % MIN_AREA = 20;
% % %
% % % cleaned = ~skel;
% % % for region = 1 : length(stats)
% % % if stats(region).Area < MIN_AREA
% % % cleaned(stats(region).PixelIdxList) = 0;
% % % end
% % % end
% % % rem = cleaned;
% % %
% % % subplot(2, 2, 3)
% % % imshow(~rem)
% % % title('Removed')
% % %
% % % %% find branches
% % % figure,
% % % rem = rem(size(rem,1)/10:size(rem, 1)-size(rem,1)/10, size(rem,2)/10:size(rem, 2)-size(rem,2)/10);
% % % [i, j] = ind2sub(size(rem), find(bwmorph(bwmorph(rem,'thin',Inf),'branchpoint') == 1));
% % % Thin = bwmorph(rem,'thin',Inf);
% % % subplot(2, 2, 1)
% % % imshow(Thin); hold on; plot(j,i,'ro');
% % % title('Branches')
% % % % % L=Thin
% % % % figure,imshow(igfDT);
% % % % [i,j] = ind2sub(size(L), find(bwmorph(L,'branchpoint') == 1));
% % % % figure,imshow(L);
% % % % [x,y]=find(L==0);
%
% mn=bwmorph(y,'branchpoints');
</pre><pre class="language-matlab">% % L=~Thin
% % input_image= imresize(input_image,size(Thin))
% % lblImg = bwlabel(L&~input_image);
% % %
% % figure,imshow(label2rgb(lblImg,'jet','k','shuffle'));
mn=bwmorph(~L,'branchpoints');
[row column] = find(mn);
branchPts = [row column];
endImg = bwmorph(~L, 'endpoints');
[row column] = find(endImg);
endPts = [row column];
figure;imshow(~L);
hold on ;
plot(branchPts(:,2),branchPts(:,1),'rx');
hold on; plot(endPts(:,2),endPts(:,1),'*');
branches = ~L & ~mn; % set branch points to zero
branchesLabeled = bwlabel( branches, 8 ); % label connected components
sts = regionprops( branchesLabeled, 'Area', 'Perimeter' ); % extract properties
figure, imshow(label2rgb(sts));
</pre>leenahttps://au.mathworks.com/matlabcentral/profile/authors/1051138-leenatag:au.mathworks.com,2005:Question/3459232017-06-23T00:22:18Z2017-06-23T02:12:18ZHow do I validate multiple linear regression with validation data?<p>I used the following code:</p><pre class="language-matlab">if true
% code
%b=regress(y,X) %returns a p-by-1 vector b of coefficient estimates for a multilinear regression of the responses in y on the predictors in X. X is an n-by-p matrix of p predictors at each of n observations. y is an n-by-1 vector of observed responses.
x1 = TrainingBootstrap;
x2 = TrainingDimension;
x3 = TrainingTNSPEC;
y = TrainingMatrix(:,4);
</pre><p>X = [ones(size(x1)) x1 x2 x3 x1.*x2 x1.*x3 x2.*x3 x1.*x2.*x3];
b = regress(y,X) % Removes NaN data
end</p><p>I got the following answer:
b =</p><pre> 1.0e+03 *</pre><pre> 1.1847
-0.0000
-0.0000
-0.0000
0.0000
-0.0000
0.0000
-0.0000</pre><p>How do I test goodness of fit of that line to validation data?</p>Cynthia Dickersonhttps://au.mathworks.com/matlabcentral/profile/authors/8326549-cynthia-dickersontag:au.mathworks.com,2005:Question/3457802017-06-22T06:57:28Z2017-06-23T02:10:13Z็How to send video object in function to GUI in Matlab<img src = "/matlabcentral/answers/uploaded_files/81134/Untitled-1.jpg"><p>I want to send video obj use for when press start program but no data to processing and I press exit and I press start again video object <b>OBJ has already been started.</b> can't processing in program</p><p>then I want to know send video obj to GUI</p>Adisorn Phanukthonghttps://au.mathworks.com/matlabcentral/profile/authors/6937939-adisorn-phanukthongtag:au.mathworks.com,2005:Question/3459292017-06-23T02:03:42Z2017-06-23T02:03:42ZHow to save global variables in MATLAB Function (more than 2) with one Data Store Memory?<p>I have 2 global variables in Matalb Function, how to save them with Data Store Memory ?</p>jingwie sunhttps://au.mathworks.com/matlabcentral/profile/authors/10258136-jingwie-suntag:au.mathworks.com,2005:Question/3459272017-06-23T01:49:34Z2017-06-23T01:49:34ZMATLAB GUI - Continuous Slider Callback<p>We have developed a GUI in Matlab to control a robot in VRML(Virtual Reality Marking Language).</p><p>We used a slider to move the robot in different frames of reference with the values getting displayed in edit text box.</p><p>How I can get the values continuously when I drag the slider?</p><p>Front panel attached for reference.</p><img src = "/matlabcentral/answers/uploaded_files/81221/panel.PNG"><p>P.S addlistener should not be used since we want to control the whole operation with single slider only.</p>Thiruvikraman Sourirajaluhttps://au.mathworks.com/matlabcentral/profile/authors/8944964-thiruvikraman-sourirajalutag:au.mathworks.com,2005:Question/3459262017-06-23T01:27:45Z2017-06-23T03:05:44Zhow can i get volume of f(x,y,z)<p>Hello, smart ladies and gentleman
I've tried to get triple integral of function below but was not work...</p><pre class="language-matlab">'Boundary condition' and 'Function' is just like that
x= 0~[210 - (40000 - (z - 799/40)^2)^(1/2)]
y= 0~[210 - (40000 - (z - 799/40)^2)^(1/2)]
z= 0~19.975
</pre><pre class="language-matlab">f(x,y,z)=(2.*3.^(1/2).*((6250000.*x.^2.*(((2.*(40000 - (z - 799./40).^2).^(1./2) - 420).*(2.*z - 799./20).^2)./(4.*((z - 799./40).^2 - 40000)) - (1./(40000 - (z - 799./40).^2).^(1./2) + ((2.*z - 799./20).*(z - 799./40))./(2.*(40000 - (z - 799./40).^2).^(3./2))).*((40000 - (z - 799./40).^2).^(1./2) - 210).^2 + ((2.*z - 799./20).^2.*((40000 - (z - 799./40).^2).^(1./2) - 210))./(4.*((z - 799./40).^2 - 40000))).^2)/((40000 - (z - 799./40).^2).^(1./2) - 210).^10 - (12500000.*(2.*z - 799./20).^2)./(((z - 799./40).^2 - 40000).*((40000 - (z - 799./40).^2).^(1/2) - 210).^14) - (6250000.*(2.*z - 799./20).^2)/(((z - 799./40).^2 - 40000).*((40000 - (z - 799./40).^2).^(1./2) - 210).^6) + (6250000.*y.^2.*(((2.*(40000 - (z - 799./40).^2).^(1./2) - 420).*(2.*z - 799./20).^2)/(4.*((z - 799./40).^2 - 40000)) - (1./(40000 - (z - 799./40).^2).^(1/2) + ((2.*z - 799./20).*(z - 799./40))/(2.*(40000 - (z - 799./40).^2).^(3./2))).*((40000 - (z - 799./40).^2).^(1./2) - 210).^2 + ((2.*z - 799./20)^2*((40000 - (z - 799./40).^2).^(1./2) - 210))./(4.*((z - 799./40).^2 - 40000))).^2)/((40000 - (z - 799./40).^2).^(1./2) - 210).^10).^(1./2))./3
</pre><p>If u guys can solve this please let me know how to solve it</p>bbagachoohttps://au.mathworks.com/matlabcentral/profile/authors/10513635-bbagachootag:au.mathworks.com,2005:Question/3321702017-03-27T16:49:33Z2017-06-23T01:17:48Zcolormap option does not work with imshow in MATLAB 2017a<p>colormap option does not work with imshow in MATLAB 2017a.</p>Vishwa Parekhhttps://au.mathworks.com/matlabcentral/profile/authors/4191596-vishwa-parekhtag:au.mathworks.com,2005:Question/3457752017-06-22T05:51:36Z2017-06-23T01:16:03ZDynamic allocation of mxArray structure<p>Hi everyone,</p><p>I have a mex function in C that internally generates an unpredictably large volume of data to be output back to Matlab. I would like the return to be a Struct Matrix of the 1 by N, where N is the unknown large number. The memory should be allocated by chunks, so that in case of insufficient memory the calculation can be stopped and the return that does fit into memory handled safely back to Matlab.</p><p>It seems that the combination of mxSetN() and mxRealloc() is a proper combination, but I can't find sufficient info on how to use mxRealloc to allocate space for additional elements of structural matrix.</p><p>Here is a minimal code example of what I'm trying to do</p><pre class="language-matlab">void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
mwSize i;
mxArray *mxp;
</pre><pre> nlhs[0]=mxCreateStructMatrix(1,1,0,NULL); //structure with one element and no fields for now</pre><pre> while (continue calculation)
{
//one more round of calculations that creates a lot of output
//stored in structure g with double* field1,..,K</pre><pre> mxAddField(nlhs[0],"field1");
mxp=mxCreateDoubleMatrix(appropriate,size,mxREAL);
if (mxp==NULL) {mexErrMsgTxt("Failed to allocate memory!")}
mxSetField(nlhs[0],i,"field1",mxp);</pre><pre> ...</pre><pre> mxAddField(nlhs[0],"fieldK");
mxp=mxCreateDoubleMatrix(appropriate,size,mxREAL);
if (mxp==NULL) {mexErrMsgTxt("Failed to allocate memory!")}
mxSetField(nlhs[0],i,"fieldK",mxp);</pre><pre> i++;</pre><pre> mxSetM(nlhs[0],i)
//What then?</pre><pre> }
} </pre>Fedor Iskhakovhttps://au.mathworks.com/matlabcentral/profile/authors/5929869-fedor-iskhakovtag:au.mathworks.com,2005:Question/3459252017-06-23T01:13:49Z2017-06-23T01:16:37ZWhat is the algorithm used by Matlab to create the Weighted KNN method on the classification App?<p>I am using the classification app on a dataset and getting a good acuracy. But I would like to use a distance measured not offered by Matlab under that option (dtw). Since I cannot change the Matlab file, I would like to know at least where they got their algorithm from or how it works so I can write a script myself and use the distance measure I want. Can anybody help?</p>Amanda Baia Camposhttps://au.mathworks.com/matlabcentral/profile/authors/8000707-amanda-baia-campostag:au.mathworks.com,2005:Question/3456002017-06-21T01:32:34Z2017-06-23T00:50:21Zbad results of my neural network _ newsgroup<p>Hi Dr Greg i tried to reply to your message in the NEWSGROUP in this link several times <a href = "https://www.mathworks.com/matlabcentral/newsreader/view_thread/348826">https://www.mathworks.com/matlabcentral/newsreader/view_thread/348826</a> but but it dosen't post , i don't know why so i decide to post it here as a question because i couldn't have any solution .</p><p>This is the message that i wanted to post :</p><p>I appology for that DR Greg this will not be repeated</p><pre class="language-matlab">> x = patientInputs;
> t = patientTargets;
> inputs = mapstd(x);
> targets = mapstd(t);
>> I don't remember suggesting mapstd. Data is automatically normalized
and unnormalized by the training function. The only reason to use mapstd
is to detect and delete or modify outliers.
</pre><p>I asked you because of the format of my inputs as you can see in this link <a href = "https://www.mathworks.com/matlabcentral/answers/344813-how-to-do-when-the-inputs-ranges-for-neural-network-are-not-so-uniform-in-magnitude">https://www.mathworks.com/matlabcentral/answers/344813-how-to-do-when-the-inputs-ranges-for-neural-network-are-not-so-uniform-in-magnitude</a>
Actually I tried to use MAPSTD but it dosen't improve so i applied the logarithme to the inputs that have a very high value numerically compared to other inputs but also it doesn't work .</p><pre class="language-matlab">> N=981
>>Why does this differ from the 1012 of previous posts?
</pre><p>It was at first 981 but i wanted to increase the number of N to see if this will improve the peformance and as i see that there is no big progress i returned to 981</p><pre class="language-matlab">> Ntrn = N-2*round(0.15*N) %
> Ntrneq = Ntrn*O %
</pre><pre class="language-matlab">>>If you are not going to use an ending semicolon, then print the answer
after the percent sign. For example
[ I N ] = size(x) % [ 9 981]
[ O N ] = size(t) % [ 2 981 ]
Ntrn = N-2*round(0.15*N) % 687
Ntrneq = Ntrn*O % 1374
</pre><pre class="language-matlab">> %For a robust design desire Ntrneq >> Nw or
> H=10
or H = 10 ???
>>That doesn't make any sense
</pre><p>This was just a typing error</p><pre> > Hub = -1+ceil( (Ntrneq-O) / (I+O+1)) % Hub =117</pre><pre class="language-matlab">>>117?? Your arithmetic sucks.
</pre><pre class="language-matlab">> Ntrials = 10
> rng(0)
> j=0
> for h =round([Hub])
</pre><pre class="language-matlab">>>Where in the world did you get that from? Hub = 114 !
</pre><pre class="language-matlab">> j = j+1
> h = h %12
</pre><pre class="language-matlab">>> h = 114! Where did you get 12 from??
</pre><p>Actually i got this value after running the code and it was from the given results</p><pre class="language-matlab">> trueclasses = vec2ind(t);
> for i = 1:Ntrials
> net = configure(net,x,t);
> [ net tr outputs errors ] = train(net,x,t);
> assignedclasses = vec2ind(outputs);
> classerr = assignedclasses~=trueclasses;
> Nerr(i,j) = sum(classerr);
> % FrErr = Fraction of Errors (Nerr/N)
> [FrErr(i,j),CM,IND,ROC] = confusion(t,outputs);
> FN(i,j) = mean(ROC(:,1)); % Fraction of False Negatives
> TN(i,j) = mean(ROC(:,2)) ; % Fraction of True Negatives
> TP(i,j) = mean(ROC(:,3)); % Fraction of True Positives
> NMSE = mse(errors)/mean(var(t',1))
> end
> end
> PctErr=100*Nerr/N
> NMSE = mse(errors)/mean(var(t',1))
</pre><pre class="language-matlab">>>This makes no sense: You have Ntrials designs but only take
the last one instead of the best one
</pre><p>the original code that i got is from you answer in this link <a href = "https://www.mathworks.com/matlabcentral/answers/130271-how-to-improve-accuracy-for-unseen-data">https://www.mathworks.com/matlabcentral/answers/130271-how-to-improve-accuracy-for-unseen-data</a></p><p>% NEURAL NETWORK MODEL</p><p>but i tried to add NMSE = mse(errors)/mean(var(t',1)) and it was a fault from me to put it after the loop.</p><p>My real problem is how can i use this result to improve the performance of my neural network So as i understand that for Not overfitting Ntrneq >= Nw so i can have idea about the limit of H because Nw = 12*H+2 and i should decrease H to have NMSE <= 0.01 * MSE00 . Ami right ?</p><p>Again i apology for this bad Etiquette but i hope that you understand me because i have no idea about neural network and Matlab and i have no time for my project this is why .</p><p>Thank you Dr greg for you patience .</p>afefhttps://au.mathworks.com/matlabcentral/profile/authors/9902982-afeftag:au.mathworks.com,2005:Question/3459242017-06-23T00:37:57Z2017-06-23T00:37:57ZHow to find the area of nearest object (surface) to the camera?<p>I'm performing a volume estimation technique using stereovision, I have a simple box shape, I managed to get the disparity map and the distance to the object. is it possible to estimate the are of the front face of the box, i.e. get the area of the surface nearest to the camera.. maybe using depth maps
thank you</p>Mohammed Subhihttps://au.mathworks.com/matlabcentral/profile/authors/8176051-mohammed-subhitag:au.mathworks.com,2005:Question/3459142017-06-22T22:16:19Z2017-06-23T00:37:21ZHow do I edit my data file<p>Hello everyone, I am having trouble outputting certain parameters out of my file. I attached the file. I want to be able to create a new file as a .dif file that can be imported into a program where I can graph my information. I want my new file to contain the *MEAS_SCAN information in column 1 with its corresponding info in column 2. For example, I want *MEAS_SCAN_AXIS_X_INTERNAL" "TWOTHETA" the rest of the information is not necessary.
I also need my file to contain all the data which I want in (x,y) format.
In total, I need to convert my new file into a different file that only has the necessary information.</p>Sharon Morganhttps://au.mathworks.com/matlabcentral/profile/authors/10483557-sharon-morgantag:au.mathworks.com,2005:Question/3459172017-06-22T22:34:53Z2017-06-23T00:22:18ZWhat is the underlying code for the 'imfindcircles' function?<p>I'm currently working on a computer vision project to measure the radii of silica microspheres based on scanning electron microscope images that I've taken. Previously, I've been using Python's openCV package to do the detection work but I find that the Matlab <b>imfindcircles</b> function works much better for my project. However, from what little I've read online, I understand that it is essentially operates using Hough transformation. That really surprises me because I was not able to get the same microsphere detection results with openCV's HoughCircles function.</p><p>Is there any way that I can see the underlying code for the <b>imfindcircles</b> function? I'm quite curious with regard to how they've implemented this function.</p><p>Thank you for your help.</p>Sandip Royhttps://au.mathworks.com/matlabcentral/profile/authors/9754183-sandip-roytag:au.mathworks.com,2005:Question/3454182017-06-19T22:00:35Z2017-06-23T00:11:00ZPresenting simultaneously 40 images, non overlapping.<p>Hi everyone,</p><p>I have a specific problem I hope you will help me with. I am running an experiment using eyetracking. In each trial (84 trials in total) I have to present 40 images, 100x100 pixels each, 20 on the right side of the screen, 20 on the left, simultaneously. The screen has a 1600x1200 pixels resolution.</p><p>I am trying to generate a random vector of coordinates of x and y which adheres the following conditions:</p><p>Each randomly generated x and y location coordinate pair must ensure the image presented is equidistant by 50 pixels from the next. This means that all the images displayed on screen, all 40 of them, must have at least 50 pixels distance from each other. So if on of the image location pairs is x = 1 and y = 1, the other x and y pairs must not have a value within x + 100(image pixel number) + 50 (distance between images) = 151, and y + 100(image pixel number) + 50 (distance between images) = 151. Each trial must have coordinate/location x and y numbers for all 40 images that adhere to these rules.</p><p>I am sorry this is so wordy. Can anyone please help?</p><p>All the best and thanks, Dritan</p>Dritan Nikollahttps://au.mathworks.com/matlabcentral/profile/authors/8302479-dritan-nikollatag:au.mathworks.com,2005:Question/3459212017-06-22T23:13:49Z2017-06-23T00:02:33ZNeed help with Scatter and colorbar,<p>Hi!
Why is the colorbar unavailable for variable z in a scatter plot?</p><p>z are values from 1000 to 4000, and I want a colorbar from those values (matrix 513x1)
I've trying with a imagesc(z), get the colorbar and use it; also, I tried with hsv2rgb, etc... but I can't...</p>Alehttps://au.mathworks.com/matlabcentral/profile/authors/9184088-aletag:au.mathworks.com,2005:Question/3459192017-06-22T22:54:38Z2017-06-22T23:51:17ZHow could I get the fit line for only the first 4 points of the graph in the following? Thank you<p>D = [0 4 8 12 16 20 24 28 32];
F = [0 .23 .36 .43 .52 .64 .78 .85 .92];
plot(D,F,'.b')
p = polyfit(D,F,1);
f = polyval(p,D);
hold on
plot(D,f,'--r')</p>Mohamed Al Shaailihttps://au.mathworks.com/matlabcentral/profile/authors/6804592-mohamed-al-shaailitag:au.mathworks.com,2005:Question/3459222017-06-22T23:16:40Z2017-06-22T23:16:40ZExport Logged Signals While Using Test Manager<p>Trying to figure out how to export the logged signals found under the "Results and Artifacts" tab after you run a test case in the Test Manager?</p>Richard Hopplehttps://au.mathworks.com/matlabcentral/profile/authors/7819349-richard-hoppletag:au.mathworks.com,2005:Question/1522011-01-18T20:35:44Z2017-06-22T23:16:10ZCan MATLAB pass by reference?<p>How does MATLAB deal with this?</p>Doug Hullhttps://au.mathworks.com/matlabcentral/profile/authors/6503672-doug-hulltag:au.mathworks.com,2005:Question/3458782017-06-22T16:50:15Z2017-06-22T23:09:58ZQuestion about major difference in computation speed with gpuArray's<p>I've been trying to optimize my code recently for a project and noticed an interesting phenomenon that occurs with it.
I have tried to google around what possibly would create it, but nothing so far has had a good answer.</p><p>The following code that runs extremely fast is:</p><pre class="language-matlab">x = linspace(-20,20,25);
z = linspace(0,100,29);
Columns =5;
singleframeofdata = gpuArray(rand(2816,128,'single'));
fgpu = gpuArray(rand(2816,1,'single'));
tofgpu = rand(length(z),length(x),128,'single');
SingleFrameOfDatarep = repmat(singleframeofdata,1,length(z)*length(x));
y = -2i*pi*-1*fgpu*reshape(tofgpu,1,size(tofgpu,1)*size(tofgpu,2)*size(tofgpu,3),1);
</pre><pre class="language-matlab">tic
holder = SingleFrameOfDatarep.*y;
toc
</pre><pre class="language-matlab">clear holder
</pre><pre class="language-matlab">tic
SingleFrameOfDatarep = SingleFrameOfDatarep.*y;
toc
</pre><p>The value of holder returns around 0.09s while SingleFrameOfDatarep will return around 0.00009s. Now i know that because the second calculation uses in place operations it will operate faster.</p><p>However, if i change x = linspace(-20,20,25) to x = linspace(-20,20,26) a drastic slow occurs.
The value of holder returns around 0.09s again while SingleFrameOfDatarep will return around 0.07s.
The original code ran ~ 770X faster than the second code.</p><p>Now my only thought/explanation on this is that when the elements of an array gets too large, matlab will create a new variable like it does for holder and this allocation time is where the slowdown occurs but i am not fully sure about this nor do i know how to test/check for this.</p><p>Could anyone point me in the correct direction to read on this or give a possible explanation/solution for this?</p>Hunter Palcichhttps://au.mathworks.com/matlabcentral/profile/authors/4541487-hunter-palcichtag:au.mathworks.com,2005:Question/3459202017-06-22T23:03:59Z2017-06-22T23:03:59ZHow to specify a Dirichlet Condition for a point within a 3D region?<p>Hi,</p><p>I am using the PDE toolbox. I would like to know what the correct formulation is for the following Laplace equation:</p><pre class="language-matlab">specifyCoefficients(model,'m',0,...
'd',0,...
'c',1,...
'a',0,...
'f',0);
</pre><p>The boundaries are adiabatic, hence Neumann conditions with q=0 and g=0 for all surfaces.
However I have the following conditions <b>within</b> the geometry:</p><pre class="language-matlab">u(x1,y1,z1) = 1
u(x2,y2,z2) = 0
</pre><p>How would I apply the above conditions given RegionType in applyBoundaryCondition only allows surfaces and edges?
applyBoundaryCondition(model,'dirichlet',RegionType,RegionID,Name,Value)</p>James Farrellhttps://au.mathworks.com/matlabcentral/profile/authors/4004127-james-farrelltag:au.mathworks.com,2005:Question/3459092017-06-22T21:19:06Z2017-06-22T22:44:37Zvision.videofilereader() produces different number of frames if run on Mac vs PC.<p>I have a number of short video clips (.mp4 and .mov) that I need to analyze frame by frame using a tool built in MATLAB. I had been noticing some discrepancies between running the code on Mac vs PC. After a lot of testing, I discovered that the problem is with the number of frames that vision.videofilereader() extracts from the video file. Here is the relevant piece of code:</p><pre> videoFileReader = vision.VideoFileReader(vfFileName);</pre><pre> obj.numFrames = 0;
obj.videoFrames = {};
while (~isDone(videoFileReader))
obj.numFrames = obj.numFrames + 1;
obj.videoFrames{end + 1} = step(videoFileReader);
end</pre><p>As an example, if I run this code on a PC it will give obj.numFrames = 71, but on a mac it will give obj.numFrames = 59 for a the same exact .mp4 file.</p><p>I did further testing on a number of .mp4 files from various sources and I found that this problem occurs if the videos were trimmed using quicktime, but not in another video editor (Bigsoft).</p><p>The best way I can explain what happens is with an example. I have an original video recorded with my camera that is 100 frames long and called myvid.mp4. I open myvid.mp4 file with Quicktime on a Mac, and trim such that I save only frames 40-60. Frames 1-39 and 60-100 are discarded. I save this new trimmed video as myvid_trimmed.mp4.</p><p>When I run the code above on myvid.mp4 on Mac or PC, I get that obj.numFrames = 100 as expected. When I run the same code on myvid_trimmed.mp4 on a mac , I get that obj.numFrames = 21 as expected. However, when I run the same code on myvid_trimmed.mp4 on a PC , I get that obj.numFrames is > 21.</p><p>When I compare the frames that were imported (obj.videoFrames above) into matlab when running the code on myvid_trimmed.mp4, I find that on a Mac, the imported frames were indeed frames 40-60 of the original myvid.mp4. However, on the PC, the imported frames seem to be 1-60. So it’s as if the lower bound of the trim never took place!</p><p>Is there any way I can get MATLAB on the PC to import the correct number of frames?
I hope my explanation makes sense. I want to thank you all in advance for taking the time to read it!</p><p>For your convenience, I have uploaded two video files as examples. The trimmed video was trimmed using Quicktime. The link can be found <a href = "https://www.dropbox.com/sh/yvb8eua3o5mfti4/AADJ8iDaD6gtJrFMh1TxeFfVa?dl=0">here.</a></p><p>More Information + things I have tried:</p><p>1) Using a trimming tool other than Quicktime isn’t an option for me, because all of the videos I need to analyze have already been trimmed, and the originals no longer exist.</p><p>2) The project involves calculating temporal data from the number of frames capturing an event, so it is very important that the frames extracted be exactly the same whether the code is being on Mac or PC</p><p>3) I have tried using videoreader() instead of vision.videofilereader() but the result is the same.</p><p>4) I have tried downloading an updated codec package from https://www.codecguide.com/, but the result is the same.</p><p>5) I ran across <a href = "https://www.mathworks.com/matlabcentral/answers/139664-different-number-of-frames-using-vision-videofilereader-and-videoreader">this</a> page in my search for a solution. There is no solution, but the OP talks about having repeated frames inserted into his video objects. So, I used some of his code that runs through each frame and compares it to the frame before, and found that none of the frames are identical. So the extra frames are not explained by duplicate frames. As I said before, the extra frames are frames that were supposed to have been trimmed.</p>William Pearsonhttps://au.mathworks.com/matlabcentral/profile/authors/5581849-william-pearsontag:au.mathworks.com,2005:Question/3459182017-06-22T22:42:26Z2017-06-22T22:42:26ZMoving-window average of a surface concentration based on the "home-range" of an animal<p>Hello,</p><p>I am working on a problem to calculate the moving-window average of a surface concentration. I created the surface concentration through kriging and have the output in a grid format spanning a large area (my grid sizes are something like a 1x1 foot and my grid is 1130x200). I need to calculate the concentration that an animal with some home-range (say 1 acre area) might be exposed to on average (to eventually display on a map).</p><p>I was wondering if anyone would have an idea of a direction I could go in or built in matlab functions to use to accomplish this task. I will need to do this over several different home-range values, so I will need to it be a fairly optimized process.</p><p>Let me know if you have any clarification questions!</p><p>Thanks for any help!
Melissa</p>Melissa Buechleinhttps://au.mathworks.com/matlabcentral/profile/authors/10481913-melissa-buechleintag:au.mathworks.com,2005:Question/3451812017-06-17T21:58:20Z2017-06-22T22:41:42ZTrouble fitting ode45<p>Have anyone find that fitting using optimization toolbox (lsqcurvefit, curvefit, etc) doesn't fit well with ode45 or the ode solvers in general? I have been playing with this for months, and I have came to a conclusion that the fitting from optimization toolbox cannot fit with ode solutions from ode library that matlab provided. I found that (maybe), the fitting can't fit is due to the variable step size (h) in the ode solver.</p>Tri Nguyenhttps://au.mathworks.com/matlabcentral/profile/authors/9644129-tri-nguyentag:au.mathworks.com,2005:Question/3453432017-06-19T13:46:54Z2017-06-23T00:38:40ZHow can I flexibly identify which check boxes are marked in a scanned document in the best way?<p>I am developing a program that processes scanned contracts and I want to extract some information from them. In these contracts there are several check boxes that may have been hand marked with an "X". I want to know which check boxes are marked and what information they represent. The issue is that there are several different versions of these contracts, so it is not just a simple matter of manually locating these check boxes and developing a "hard-coded" solution. I have to:</p><ol><li>Loop through the contract files (which are binary images located in a database as .tif images)</li><li>For each contract, identify which contract type it is</li><li>Given 2), run an algorithm to extract the important information from this contract</li></ol><p>My current idea of strategy for 2) is to use some kind of correlation by referencing every loaded contract against a library of all possible templates. However, since the scanned contracts might be slightly different in size, corr2 is not working very well unless I use some indexing in one of the images, i.e. something like corr2(I(1:xsize(J),1:ysize(J)),J), but I'm not sure if that's a good idea. Is there a smarter way to do this, i.e. maybe using xcorr?</p><p>For issue 3) I have adapted a modified version of the object recognition algorithm given by ImageAnalyst here <a href = "https://se.mathworks.com/matlabcentral/answers/156559-detect-horizontal-and-vertical-lines">https://se.mathworks.com/matlabcentral/answers/156559-detect-horizontal-and-vertical-lines</a>, where my idea is to identify the check boxes and use their location to identify what information they represent. I am using regionprops with bounding boxes to find my check boxes. Given these bounding boxes, I use some measures like height, eccentricity and aspect ratio to find the check boxes. It works fine, but unless I use very hard-coded constraints to identify the check boxes for each sample contract I am working on, I get instances of text identified as objects as well. See the attached image for an example ("kt" and "M" are the text instances I get). Is there a smarter way to identify these types of objects that is much more reliable? If anyone has any idea of how I can tackle this issue better it is much appreciated.</p><img src = "/matlabcentral/answers/uploaded_files/80877/identifiedboxes.jpg">SofiaHhttps://au.mathworks.com/matlabcentral/profile/authors/6979636-sofiahtag:au.mathworks.com,2005:Question/3459032017-06-22T20:37:25Z2017-06-22T22:35:31ZCan anyone help me why this code gives me this error " In EnhanceMulticolorImages1 (line 41) Error using imread>parse_inputs (line 445) The file name or URL argument must be a character vector.? I need to calculate the % intensity of each color. <pre class="language-matlab">[filename, pathname] = uigetfile( ...
{'*.*','All Files (*.*)'}, ...
'Pick a file','C:\Users\gnya01\Desktop\Backup from L drive\DermaScope Images'); %Change Based on where you want default location
%Load image;
imname409=uigetfile('*.jpg','select jpg image',pathname);
truecolor =imread(strcat(pathname,imname409));
figure
imshow(truecolor);
title('Truecolor Composite (Un-enhanced)')
text(size(truecolor,2), size(truecolor,1) + 15,...
'Image courtesy of Space Imaging, LLC',...
'FontSize', 7, 'HorizontalAlignment', 'right');
%By viewing a histogram of the red band, for example, you can see that the data is concentrated within a small part of the available dynamic range. This is one reason why the truecolor composite appears dull.
figure
imhist(truecolor(:,:,1))
title('Histogram of the Red Band (Band 3)');
%Another reason for the dull appearance of the composite is that the visible bands are highly correlated with each other. Two- and three-band scatterplots are an excellent way to gauge the degree of correlation among spectral bands. You can make them easily just by using plot.
r = truecolor(:,:,1);
g = truecolor(:,:,2);
b = truecolor(:,:,3);
figure
plot3(r(:),g(:),b(:),'.')
grid('on')
xlabel('Red (Band 3)')
ylabel('Green (Band 2)')
zlabel('Blue (Band 1)')
title('Scatterplot of the Visible Bands');
</pre><pre class="language-matlab">%When you use imadjust to apply a linear contrast stretch to the truecolor composite image, the surface features are easier to recognize.
stretched_truecolor = imadjust(truecolor,stretchlim(truecolor));
figure
imshow(stretched_truecolor)
title('Truecolor Composite after Contrast Stretch');
%A histogram of the red band after applying a contrast stretch shows that the data has been spread over much more of the available dynamic range.
figure
imhist(stretched_truecolor(:,:,1))
title('Histogram of Red Band (Band 3) after Contrast Stretch');
%Another way to enhance the truecolor composite is to use a decorrelation stretch, which enhances color separation across highly correlated channels. Use decorrstretch to perform the decorrelation stretch (followed by a linear contrast stretch, as specified by the optional parameter-value pair 'Tol' and 0.1).
decorrstretched_truecolor = decorrstretch(truecolor, 'Tol', 0.4);
figure
imshow(decorrstretched_truecolor)
title('Truecolor Composite after Decorrelation Stretch');
%As expected, a scatterplot following the decorrelation stretch shows a strong decrease in correlation.
r = decorrstretched_truecolor(:,:,1);
g = decorrstretched_truecolor(:,:,2);
b = decorrstretched_truecolor(:,:,3);
figure
plot3(r(:),g(:),b(:),'.')
grid('on')
xlabel('Red (Band 3)')
ylabel('Green (Band 2)')
zlabel('Blue (Band 1)')
title('Scatterplot of the Visible Bands after Decorrelation Stretch');
% %Construct a CIR composite by reading from the original LAN file and composing an RGB image that maps bands 4, 3, and 2 to red, green, and blue, respectively.
% CIR = multibandread('paris.lan', [512, 512, 7], 'uint8=>uint8', ...
% 128, 'bil', 'ieee-le', {'Band','Direct',[4 3 2]});
% %Even though the near infrared (NIR) band (Band 4) is less correlated with the visible bands than the visible bands are with each other, a decorrelation stretch makes many features easier to see.
stretched_CIR = decorrstretch(truecolor, 'Tol', 0.1);
figure
%img1 = imshow(stretched_CIR);
%title('CIR after Decorrelation Stretch');
%A property of color infrared composites is that they look red in areas with a high vegetation (chlorophyll) density. Notice that the Bois de Boulogne park is red in the CIR composite, which is consistent with its green appearance in the decorrelation-stretched truecolor composite.
img1 = imread(stretched_CIR);
imh = imshow(img1);
% Create a mask using freehand ROI
img1 = imwrite(stretched_CIR, truecolor);
imshow(test);
h = imfreehand;
m = createMask(h, img1);
%delete(h)
% Extract individual color channels
r = img1(:,:,1);
g = img1(:,:,2);
b = img1(:,:,3);
% Get sum of intensity of each channel
r_s = sum(r(m));
g_s = sum(g(m));
b_s = sum(b(m));
% Calculate percentage of intensity of each color
r_p = r_s / (r_s + g_s + b_s) * 100;
g_p = g_s / (r_s + g_s + b_s) * 100;
b_p = b_s / (r_s + g_s + b_s) * 100;
</pre>Surya Gnyawalihttps://au.mathworks.com/matlabcentral/profile/authors/2545146-surya-gnyawalitag:au.mathworks.com,2005:Question/3458582017-06-22T14:56:18Z2017-06-22T22:34:52ZProduct of an FFT with a Gaussian filter and subsequent display issues<p>Hi, I am trying to display a product of two images (an FFT and a Gaussian filter) and then an inverse FFT of that product.
I seem to be having issues with the display and it's quite possible the code is incorrect!</p><p>I attach the output and the output I can get in a separate program (digital micrograph).</p><p>Clearly they are different and I want to find out why.</p><p><b>Here is my code:</b></p><p><i>%script to multiply an FFT with a filter</i></p><p><i>%Read FFT as a UINT8 file and display</i></p><p>FFT=imread('FFT_of_frame-1.tif');</p><p>subplot(2,2,1);</p><p>imshow(FFT);</p><p><i>%Read DGF as a UINT8 file and display</i></p><p>DGF=imread('DoubleGaussian_1.tif');</p><p>subplot(2,2,2);</p><p>imshow(DGF);</p><p><i>%multiply FFT an DGF together and display result</i></p><p>FFT_filt=immultiply(FFT,DGF);</p><p>subplot(2,2,3);</p><p>imshow(FFT_filt,[]);</p><p><i>%display Inverse FFT of FFT_filt and display</i></p><p>IFFT=ifft2(FFT_filt);</p><p>IFFT_display=uint8(real(IFFT));</p><p>subplot(2,2,4);</p><p>imshow(IFFT_display);</p><p><b>end of code.</b></p><p>Thanks in advance!</p>Eoghan O'Connellhttps://au.mathworks.com/matlabcentral/profile/authors/10476110-eoghan-o-connelltag:au.mathworks.com,2005:Question/3448132017-06-14T21:33:11Z2017-06-22T22:34:35ZHow to do when the inputs ranges for neural network are not so uniform in magnitude ?<p>Hi,i'm trying to create neural network for classification of EEG signal in which i extacted 9 features that i will use it as inputs for neural network but the problem is that my inputs ranges are not so uniform in magnitude i mean some input can take a very high value numerically compared to other inputs so the big numbers will mask the effect of the smaller numbers.
I used the preprocessing function 'mapminmax' but i still have a bad performance so when i do some research i found that i should Transform each input that has always a positive value into logarithm values. Matlab will take these transformed values and apply the normalization to them [-1,1]. For prediction, i should enter not the actual values but the logarithm of the input to the ANN.
So i want tp know is this right ? and can i do this transformation of my innputs with matlab?</p><p>This how my original input looks like</p><img src = "/matlabcentral/answers/uploaded_files/80518/11.png">afefhttps://au.mathworks.com/matlabcentral/profile/authors/9902982-afeftag:au.mathworks.com,2005:Question/3459162017-06-22T22:31:40Z2017-06-22T22:31:40ZNon-Rigid Registration of 3D Points<p>I am looking for a way to perform non-rigid registration on 3d point cloud data. The data only includes the x,y,z locations of each point. Something similar to pcregrigid would be ideal but that is a non-rigid transformation. I have also considered converting the point cloud to an image and then using imregdemons to achieve a similar result. However, I am unsure of how to convert the point cloud data to an image. Any suggestions on either approach would be greatly appreciated.</p>Andrew Hallhttps://au.mathworks.com/matlabcentral/profile/authors/6115287-andrew-halltag:au.mathworks.com,2005:Question/3459102017-06-22T21:44:19Z2017-06-22T22:30:02ZPredict curve for know area under the curve<p>The value of Y varies with X as a polynomial function - (1). Y = A + B/T, where T is temperature and it linearly increases with X. I want to find a Temperature (Te), where the area under the curve of the polynomial function - (1) is equal to the area under the linear curve for Y at Te versus X.
Attached is the graph- Need to find a Y value where the area under the blue line becomes equal to the area under the polynomial function.</p><img src = "/matlabcentral/answers/uploaded_files/81207/Matlab_area.png">AluAlhttps://au.mathworks.com/matlabcentral/profile/authors/7532669-alualtag:au.mathworks.com,2005:Question/3459152017-06-22T22:28:42Z2017-06-22T22:28:42Zbdttree - Tree building failed to converge for level 5 of BDT Tree<p>I am trying to build a 5-year BDT tree (monthly step) using bdttree function. The risk free rate and volatility assumptions are in the attached file. I am getting a warning saying "Tree building failed to converge for level 5
of BDT Tree". If I use quarterly step, there is no problem. However, I have to use monthly step to capture optionality of the instrument I am trying to value, but it does not work. I have pasted my code below. Could anyone help me understand what the problem is and how to fix it? Thanks!</p><pre class="language-matlab">if true
% code
%% Contractual Terms
valDate = datenum('4/13/2017');
IssueDate = datenum('4/13/2017');
FirstCouponDate = datenum('5/5/2017');
MaturityDate = datenum('4/13/2022');
freq = 12;
%% Risk-free rates & Vols
data = csvread('bdttree inputs.csv',1,0);
data_rates = data(:,2)/100;
data_vols = data(:,3)/100;
data_term = data(:,1);
data_rates = freq*((1+data_rates).^(1/freq)-1);
%% Construct BDT tree
bdtDates = cfdates(valDate, MaturityDate, freq, 1,1,IssueDate,FirstCouponDate)';
t = yearfrac(valDate,bdtDates,1);
Rates = interp1(data_term, data_rates, t,'linear');
Vols = spline(data_term, data_vols, t);
BDTVolSpec = bdtvolspec(valDate, bdtDates, Vols);
RateSpec = intenvset('Compounding', freq,...
'ValuationDate', valDate,...
'StartDates', valDate,...
'EndDates', bdtDates,...
'Rates', Rates);
BDTTimeSpec = bdttimespec(valDate, bdtDates, freq);
BDTTree = bdttree(BDTVolSpec, RateSpec, BDTTimeSpec);
</pre><pre class="language-matlab">end
</pre>wallehttps://au.mathworks.com/matlabcentral/profile/authors/10513218-walletag:au.mathworks.com,2005:Question/3453192017-06-19T11:07:17Z2017-06-22T22:25:23ZHow to get black pixels and display them in static text <p>I have an gray scale image and i want to know the total number of pixels, the number of black pixels, and display them in static text GUI. But i can't get the results to show in the static text.</p><pre class="language-matlab">a = handles.grey;
b = handles.imgData;
B = img2double(b);
A = im2double(a);
</pre><pre class="language-matlab">% black pixels
c = sum(A(:) == 0);
</pre><pre class="language-matlab">textLabel2 = sprintf(c);
set(handles.areaporos, 'String', textLabel2);
</pre><pre class="language-matlab">% total pixels
numPixels = numel(B);
</pre><pre class="language-matlab">textLabel = sprintf(numPixels);
set(handles.areatotal, 'String', textLabel);
</pre><p>Can someone help me figure out what I'm doing wrong? Thank you!</p>sofia cirnehttps://au.mathworks.com/matlabcentral/profile/authors/4781023-sofia-cirnetag:au.mathworks.com,2005:Question/3458832017-06-22T17:23:37Z2017-06-22T22:24:13ZHi I need a function to normalize my excel file in Matlab between zero and one I need input and output, the name of the file is softwareadyfornormalization and the excel file is 26 * 7 table it is my first time using matlab sorry for the mess<p>function z</p><p>function Z = normalization
Z = ('softwareadyfornormalization');</p><p>for i = 1 : size(Z,2)
MaxValue = max(Z(:,i));
MinValue = min(Z(:,i));
Z(:,i) = Z(:,i)/(MaxValue - MinValue);</p><p>end</p>Emmanuel Fajuyigbehttps://au.mathworks.com/matlabcentral/profile/authors/10261441-emmanuel-fajuyigbe