https://cn.mathworks.com/matlabcentral/answers/questions.atomMATLAB Answers — New Questions2017-11-22T16:44:39Ztag:cn.mathworks.com,2005:Question/3684152017-11-21T16:24:36Z2017-11-22T16:44:02ZAs the administrator of a Windows PC, can I create a Matlab code that a user can execute, but that this user cannot neither read nor copy?<p>Example:
I write a code AAA.m, which calls another one, BBB.m.
I want the user the be able to edit/modify AAA.m and to run it, which needs Matlab to be able to call BBB.m, but I want to prevent the user from reading and copying BBB.m.</p>Franck Tancrethttps://cn.mathworks.com/matlabcentral/profile/authors/2888046-franck-tancrettag:cn.mathworks.com,2005:Question/3686092017-11-22T14:45:10Z2017-11-22T16:43:21ZHow to mute or silence part of an audio file being used in Matlab's audioplayer?<p>Hi there, I have imported an audio file into Matlab which has configured it as <b>(data, fs)</b> in the workspace. I am using <b>p=audioplayer(data, fs);</b> to play this audio file. I am using <b>y=data</b> and <b>plot(y)</b> to see this audio file on the axis. I need to mute or silence a specific section, in samples, of this file and see the result on the axis. Any ideas how to achieve this?</p>Chris79https://cn.mathworks.com/matlabcentral/profile/authors/11019350-chris79tag:cn.mathworks.com,2005:Question/3686322017-11-22T15:54:54Z2017-11-22T16:42:46ZIIR and FIR Bandpass Filter Design Help (2.2kHz) from a .wav<p>I'm trying to develop a filter to remove a 2.2kHz tone from a voice recording (.wav). I'm looking at a lot of responses, but not finding anything that's working.</p><p>https://www.mathworks.com/matlabcentral/answers/317340-how-to-filtre-an-audio-signal-with-low-pass-filtre</p><p>This seems to be a good approach, but I need a bandpass filter.</p><p>Would someone help me through this? The .wav and a frequency spectrum are provided. This is how I extracted the frequency plot.</p><p>clc, clear all, close all;</p><p>[y,Fs] = audioread('HornAudioECE450.wav');</p><p>stepSize = 1/Fs;</p><p>L = length(y);</p><p>t = 0:stepSize:(length(y)*stepSize - stepSize);</p><p>f = linspace((-Fs/2),(Fs/2),L);</p><p>figure()</p><p>plot(t,y);</p><p>Y = fftshift(abs(fft(y)./2));</p><p>plot(f,Y);</p>Kevin Hornhttps://cn.mathworks.com/matlabcentral/profile/authors/11485556-kevin-horntag:cn.mathworks.com,2005:Question/3686172017-11-22T14:59:34Z2017-11-22T16:42:27Zfor loop only through certain elements of an array<p>Hello all,</p><p>I would like to do this more time efficiently. Lets say I have a 4D (xn,yn,zn,N) data array and a 3D (xn,yn,zn) mask array. I would like to go through 4D array and calculate something from the numbers in the 4th dimension, but I want only elements from the mask. Is there a way of doing this more efficiently, than going through xn*yn*zn elements and checking if they are withing the mask?</p><p>This is the brute force way:</p><pre class="language-matlab">for x=1:xn
for y=1:yn
for z=1:zn
if mask(x,y,z)==1
do something with data(x,y,z,:);
end
end
end
end
</pre><p>Thank you.</p><p>Edit: I think I need to explain the task at hand better. The 4D data is several 3D images combined along the 4th dimension, which corresponds to certain image acquisition parameters. I want to do</p><p>f=fit(Par, data(x,y,z,:), 'exp1');</p><p>for each image voxel from the mask.</p>Renathttps://cn.mathworks.com/matlabcentral/profile/authors/303556-renattag:cn.mathworks.com,2005:Question/3684782017-11-21T23:15:06Z2017-11-22T16:44:39ZHow can I loop a DICOM and corresponding ROI folder and write results to a .csv<p>I have a directory with 60 CT-DICOM images (named F000001.dcm, F000002.dcm ...) and another directory with 60 correspoding region of interests (ROI) in NIFTI format (named 1.nii, 2.nii ...).</p><p>I need to get the mean hounsfield unit (HU) for every DICOM and corresponding ROI.</p><p>I managed to get the right value for one DICOM, however, I do not exactly know how to loop through the DICOM and ROI folder and save all results automatically to a csv with col1=filename and col2=meanHU</p><pre class="language-matlab">close all;
clear all;
% The dicom filename
folderFileName = '.\DICOM\F000001.dcm';
% Read the dicom header info
dinfo = dicominfo(folderFileName);
% Read the dicom image data and rescale to the correct values
myImage = double(dicomread(folderFileName))*dinfo.RescaleSlope + dinfo.RescaleIntercept;
% read the transformed roi
ROI = '\ROI\1.nii'
% extract mean HU:
values = myImage(ROI);
meanHU = mean(values)
</pre>Urs Mühlematterhttps://cn.mathworks.com/matlabcentral/profile/authors/7071518-urs-muhlemattertag:cn.mathworks.com,2005:Question/276682012-02-01T08:55:42Z2017-11-22T16:39:41ZExhaustive Block Matching Algorithm<p>Hi all,</p><p>I'm trying to write the Exhaustive Block Matching Algorithm based on the pseudo-code written in this slide: <a href="http://inst.eecs.berkeley.edu/~ee290t/sp04/lectures/motion_estimation.pdf">http://inst.eecs.berkeley.edu/~ee290t/sp04/lectures/motion_estimation.pdf</a></p><p>I think I wrote my programme not correctly but don't know where I was wrong. Can anyone please help me? Thank you very much :(</p>Tuan Nguyenhttps://cn.mathworks.com/matlabcentral/profile/authors/2869422-tuan-nguyentag:cn.mathworks.com,2005:Question/3686442017-11-22T16:38:11Z2017-11-22T16:38:11ZHow to extract RGB values of each pixel from an image?<p>I need to extract the RGB values of each pixel of a given image in a serial data format.</p>Ankit Bhattacharyyahttps://cn.mathworks.com/matlabcentral/profile/authors/5638602-ankit-bhattacharyyatag:cn.mathworks.com,2005:Question/3684642017-11-21T21:34:15Z2017-11-22T16:36:22Zdeleting leadind and trail zeros in an image<p>Hi all
I am working on enhancing a grayscal images, the first step should be cropping the image by removing lead and trail zeros (zeros rows an columns surrounding the image). i want t remove the surrounding zeros. please be advised that the cropping has be applied on zeros rows and columns that surrounding the image for different images, so i need a function or an algorithm does this cropping on different images.
thanks in advance</p>Hassan Qassimhttps://cn.mathworks.com/matlabcentral/profile/authors/10890700-hassan-qassimtag:cn.mathworks.com,2005:Question/3686432017-11-22T16:35:08Z2017-11-22T16:35:08ZHow to plot a numerical integral using the trapezoidal method<p>I want to plot a figure based on an equation. The equation in mind is composed of two terms. The first term is a simple equation, consisting of different parameters. But, the second equation with the same parameters, is an integral which has to be taken into account numerically. Of the numerical methods, I used the trapezoidal method. I'm working with the following code:</p><pre> clc
clear all
close all
e=1.60217662d-19;
kB=1.3806488d-23;
h=6.62607004d-34;
hbar=h/(2*pi);
T=300;
R=kB*T;
tau=0.0658d-12;
gamma=1/tau;
vf=1d6;
omega=2*pi*1d12*(0:0.1:10);
uc=e*[0.01,0.015,0.02];
for k=1:length(omega)
for n=1:length(uc)
D=(e^2)/(4*hbar);
eps=e*(0:0.01:10);
W1=1./(1+exp((eps-uc(n))/(R)));
W2=1./(1+exp((-eps-uc(n))/(R)));
W=W2-W1;
E=(1i*(e^2))/(pi*hbar^2);
sigma_inter(k,n)=trapz(eps,(E*(omega(k)+1i*gamma)*W)./((omega(k)+1i*gamma)^2-4*(eps/hbar).^2));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
A=(uc(n)/R)+2*log(1+exp(-uc(n)/R));
B=(1i*(e^2)*R)/(pi*hbar^2);
C=omega(k)+1i*gamma;
sigma_intra(k,n)=(A*B)./C;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
sigma(k,n)=(sigma_intra(k,n)+sigma_inter(k,n))/D;
end
yyaxis left
plot(omega/(1d12*2*pi),imag(sigma(k,n)));
ylabel('Im[\sigma]');
yyaxis right
plot(omega/(1d12*2*pi),real(sigma(k,n)));
ylabel('Re[\sigma]');
xlabel('Frequency (THz)');
title('Graphene Surface Conductivity');
end</pre><p>When plotting the imaginary and real parts of the equation, the figures are weird. As it seems, the dimensions of some parameters are not in agreement with each other. so I think, it's all about the dimensionality. But I have no idea how to resolve this problem.</p>Mahdi Yavarianhttps://cn.mathworks.com/matlabcentral/profile/authors/11583256-mahdi-yavariantag:cn.mathworks.com,2005:Question/3686422017-11-22T16:32:17Z2017-11-22T16:32:17Zhow can i get license key for R2015?<p>I need MATLAB R2015a version.While trying to install this software,it asks for license number or activation key.I don't have any license number and activation key.Please provide me license number for MATLAB R2015a.</p>jane customerhttps://cn.mathworks.com/matlabcentral/profile/authors/10716425-jane-customertag:cn.mathworks.com,2005:Question/3686362017-11-22T15:57:59Z2017-11-22T16:27:51Zhow to divide an EEG signal into segments <p>Hello,
I have an EEG signal of 124s (of extension .m and length (x) = 20000) that I want to divide into segments of specific length (in s), I have the moment of the beginning and the end of each desired segment in seconds.</p>Sana Arfaouihttps://cn.mathworks.com/matlabcentral/profile/authors/11554564-sana-arfaouitag:cn.mathworks.com,2005:Question/3686412017-11-22T16:27:08Z2017-11-22T16:27:08ZAdd more latex packages for latex interpreter in Matlab<p>Hi,</p><p>is it possible to include the "amssymb" package for the latex interpreter.
I want to use the $\square$ latexcommand in a plot legend.
All solutions with modify matlabsystemfiles like tex.m does not work.
I use Matlab 2017a.</p><p>Thanks for a solution</p>ChrisCrosshttps://cn.mathworks.com/matlabcentral/profile/authors/8411494-chriscrosstag:cn.mathworks.com,2005:Question/3686402017-11-22T16:26:57Z2017-11-22T16:27:24ZSimulation data inspector doesn't work in accelerator mode<p>Hi everyone,</p><p>my matlab version is R2015aSP1. When I run the simulink model in Normal mode, the data inspector works well. However, in accelerator mode it doesn't show any signal results.</p><p>I tried to use the following command to solve this problem. But it didn't help.</p><pre class="language-matlab">sdi.Repository.clearRepositoryFile();
</pre><p>Any suggestions would be highly appreciated.</p><p>Thank you!</p>Xiaojie Qiuhttps://cn.mathworks.com/matlabcentral/profile/authors/11348003-xiaojie-qiutag:cn.mathworks.com,2005:Question/3686392017-11-22T16:22:58Z2017-11-22T16:22:58Zinterpolating curve with tangent ends<p>Hello,
I need to construct interpolating curve from data points (I have 3 points in plane) with tangent ends. I know derivative at the ends (in points 1 and 3).
Could anybody advise how to do it?</p><p>Thanks,
Michal</p>Michal Lukachttps://cn.mathworks.com/matlabcentral/profile/authors/1053300-michal-lukactag:cn.mathworks.com,2005:Question/3686112017-11-22T14:46:40Z2017-11-22T16:17:50ZCalculating gradient of a matrix - too many outputs... Not sure why?<p>Hello,</p><p>I have calculated a result matrix using the integrating function on matlab, however when I try to calculate the gradient of the result matrix, it says I have too many outputs.</p><p>My code is as follows:</p><pre class="language-matlab">x = linspace(-1,1,40);
y = linspace(-2,2,40);
</pre><pre class="language-matlab">for ii = 1:numel(x);
</pre><pre> for jj = 1:numel(y)</pre><pre> fun = @(x) x(ii) + y(jj)</pre><pre> V(ii,jj) = integral(fun, 0, 2());
end
end</pre><pre class="language-matlab">[qx,qy] = -gradient(V);
</pre><p>I tried to set up a meshgrid first to do my calculation over x and y, however the integral matlab function couldn't handle a meshgrid.</p><p>Any idea how I could calculate the gradient of my resulting V function?</p><p>Note that I have replaced my actual function with a more simple function. I could not calculate the integral of my function directly and thus am resorting to numerical integration.</p>Mark Lepagehttps://cn.mathworks.com/matlabcentral/profile/authors/10139950-mark-lepagetag:cn.mathworks.com,2005:Question/3684342017-11-21T17:41:43Z2017-11-22T16:17:05ZGUI check state of radio button in another callback<p>I have a push button callback, and a selection of radio buttons. Within the push button I want to be able to say</p><pre class="language-matlab">if radio1 selected
% code
else if radio 2 selected
% do
end
</pre><p>This would naturally have to update whenever the radio button selection was changed.</p><p>How would I do this?</p>Nicholas Willshttps://cn.mathworks.com/matlabcentral/profile/authors/9079208-nicholas-willstag:cn.mathworks.com,2005:Question/3685792017-11-22T11:49:48Z2017-11-22T16:11:20Zapproximate lines from both edges of a point cloud in 2D<img src = "/matlabcentral/answers/uploaded_files/95665/untitled.jpg"><p>I am looking for an approximation of the two lines in black (I added them manually),to find their intersection.
could anyone help me?</p>ameni mkawarhttps://cn.mathworks.com/matlabcentral/profile/authors/8425774-ameni-mkawartag:cn.mathworks.com,2005:Question/3686012017-11-22T14:11:14Z2017-11-22T16:11:11ZPlot a curve as a vertical 3D surface in MATLAB?<p>I have two vectors of data, say x and y, corresponding to the discrete x and y coordinates of a curve in 2D space. I want to plot this curve with a fixed height, say z = 1, in 3D to form a surface. (The goal is to visualize the intersection of this surface with another surface plot). Below is an image that depicts what I want to do. Any ideas on how this could be accomplished?</p><img src = "/matlabcentral/answers/uploaded_files/95676/20171122_080413.jpg">Preston Quinehttps://cn.mathworks.com/matlabcentral/profile/authors/8577076-preston-quinetag:cn.mathworks.com,2005:Question/3686032017-11-22T14:20:05Z2017-11-22T16:10:30Zsensitivity analysis for nonlinear inventory model<p>hi, I need to do table and graph for sensitivity analysis for nonlinear inventory model. I have found the optimal value using Genetic Algorithms.how can i do it in MATLAB. thank you all</p>sarah abdhttps://cn.mathworks.com/matlabcentral/profile/authors/8563052-sarah-abdtag:cn.mathworks.com,2005:Question/3686382017-11-22T16:09:34Z2017-11-22T16:09:34ZI have a script that I run via a timer every 30 minutes -- how do I run this in background?<p>My script runs on a timer every 30 minutes, and I realize I need to run this in background so I can continue to use Matlab for other work. How do I run this timer script in background?</p>Robert Hensonhttps://cn.mathworks.com/matlabcentral/profile/authors/9494764-robert-hensontag:cn.mathworks.com,2005:Question/3686182017-11-22T15:00:17Z2017-11-22T16:09:19ZWhy using genetic algorithm at the end of max generation i get the best value of the last generation and not the best value find so far?<p>I'm using GA to optimize parameters of a neural network such as number of neurons, best architecture, best TransfFnc best TrainFnc and so on. It works fine but the problem is that at the end of the optimization (after maxgenerations is reached) I obtain a value (fitnessfunction is set to use the performance of the network) that is not the best value find during the whole optimization. I've been keeping notes (manualy) everytime a good value comes out (such as 1.2e-4) and at the end, when GA stops I get always a worse (higher) value (like 3.5e-4). My question is: is there a way to tell GA to give me the best value (and parameters) found among ALL generations and not only among the last one?
Thank you very much for your kind attention.</p>MLUtility767https://cn.mathworks.com/matlabcentral/profile/authors/9726590-mlutility767tag:cn.mathworks.com,2005:Question/3686292017-11-22T15:30:53Z2017-11-22T16:09:18ZCheck elements in cell <p>Hello, I have this cell:</p><pre class="language-matlab">[] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] 'Del Col_2010' [] [] [] [] 'Lee&Mudawar_2005'
</pre><p>and I have written this code:</p><pre class="language-matlab">for z=1:length (NAME_T)
if isequal(NAME_T,'Del Col_2010')
disp ('YES')
else
disp ('NO')
end
end
</pre><p>But the answer is always NO. What can i do?
THanks in advance.</p>Palumbo Pierohttps://cn.mathworks.com/matlabcentral/profile/authors/11340285-palumbo-pierotag:cn.mathworks.com,2005:Question/3355662017-04-15T23:05:40Z2017-11-22T16:06:54Zhelp for "live script"<p>I have a problem with "live script"file. When I open a "live script" file,there is a "loading" light that is always wheel around and never disappear. I atteched a picture about with this problem</p><img src = "/matlabcentral/answers/uploaded_files/75234/problem.JPG">hatem çobanhttps://cn.mathworks.com/matlabcentral/profile/authors/9032080-hatem-cobantag:cn.mathworks.com,2005:Question/3686192017-11-22T15:11:00Z2017-11-22T16:06:39ZHow to find parameters for Simbiology ?<p>I am an iGEMer focus on modeling. But rather than building a model, it is finding parameters that trouble me most. How to find parameters quickly and efficiently? Is there any parameter database?
Thanks a lot for your help.</p>Victor Kanghttps://cn.mathworks.com/matlabcentral/profile/authors/10881804-victor-kangtag:cn.mathworks.com,2005:Question/3682162017-11-20T21:29:48Z2017-11-22T16:03:08ZWhy does legacy code scale variables by 2^16?<p>I am trying to understand some legacy Matlab code, and was puzzled to note that many variables are multiplied or divided by 2^16. After some digging I found this is the largest number that a 16-bit (unsigned) integer can hold, see <a href = "https://softwareengineering.stackexchange.com/questions/42269/why-is-216-a-special-number">here</a>. I believe the code originated in C or C#. I have two questions: (1) Could the code author be using this factor to force the variable to be a float? (2) If so, can I delete all the 2^16 factors without affecting the values in Matlab?</p><p>Here is an example,</p><pre class="language-matlab">SOME_THRESHOLD = floor(0.010 * 65536); % Author's comment indicates this is supposed to represent 10%
</pre><p>SOME_THRESHOLD gets passed in to a function which where all the other variables have been multiplied by either 65536 or 2^16 prior to arithmetic operations; floor and abs are also used.</p>KAEhttps://cn.mathworks.com/matlabcentral/profile/authors/9495793-kaetag:cn.mathworks.com,2005:Question/3685482017-11-22T08:48:08Z2017-11-22T16:02:21ZFinding limits such that integral achieves desired value<p>Hello,</p><p>I want to find the upper limit of an integral such that the desired value is obtained. I have found a way, but I would like to reduce computation time. Could you please suggest alternate functions/methods?</p><p>syms T upper_lim;</p><p>acc_indef = -2.5*T;</p><p>T0=solve(int(acc_indef,T,0,upper_lim)+5==0,upper_lim);</p><p>This is a simple integral whose upper limit is to be calculated such that the value of the integral is -5...</p><p>Thanks in advance :)</p>RPatelhttps://cn.mathworks.com/matlabcentral/profile/authors/4806285-rpateltag:cn.mathworks.com,2005:Question/3686372017-11-22T16:02:21Z2017-11-22T16:02:21ZData shift with least squares regression<p>Hi everyone,</p><p>I have 10 sets of data (repetitions of same experiment) which start at different times. I'd like to align them using a least squares regression.</p><img src = "/matlabcentral/answers/uploaded_files/95698/example%20question%202.png"><p>I haven't found any documentation to use lsqnonlin without having a function input, so I'm not sure on how to approach it.</p><p>Any suggestions?</p><p>Thanks!</p>Natalia Perez del Postigo Prietohttps://cn.mathworks.com/matlabcentral/profile/authors/7647845-natalia-perez-del-postigo-prietotag:cn.mathworks.com,2005:Question/3685372017-11-22T07:40:01Z2017-11-22T15:59:06ZI have an Image shown below as 'a' ,after extracting co-ordinates of certain pixels , based on some specified criteria. when I am changing the colour of those coordinates in oriinal image I am getting different type of image.? ,<img src = "/matlabcentral/answers/uploaded_files/95641/untitled.jpg"><img src = "/matlabcentral/answers/uploaded_files/95642/untitled1.jpg">Mohammad Bhathttps://cn.mathworks.com/matlabcentral/profile/authors/5232683-mohammad-bhattag:cn.mathworks.com,2005:Question/3684262017-11-21T17:28:35Z2017-11-22T15:58:58ZHow to know whether it is an image or a website with a given url?<p>Hi</p><p>I have a few urls, each of which begin with 'http://' and end with '.jpg'.</p><p>e.g. <a href = "http://anguerde.com/pics/main/2/218886-active.jpg">http://anguerde.com/pics/main/2/218886-active.jpg</a></p><p>Some lead to images and others lead to websites (e.g. the above url).</p><p>Is there a way to know whether each url leads to an image or a website? If it leads to an image, save it; if it leads to a website, do nothing.</p><p>Can anyone help?</p>Salad Boxhttps://cn.mathworks.com/matlabcentral/profile/authors/11434690-salad-boxtag:cn.mathworks.com,2005:Question/3686352017-11-22T15:56:58Z2017-11-22T15:56:58Zcould anybody help me to execute the following code<p>// comments</p><ol><li>include <a href = "math.h">math.h</a></li><li>include "mex.h"</li></ol><p>void greedyAlgSingleUser(
double requiredRate, // in, the required bits/sec/Hz for user
double *channelStateInformation, // in, the channel state information
mwSize numOfLevels, // in, the length of discrete levles
// of bitrate based on modulation, for example the BBSK,QPSK,MQAM
double *levelsRate, // in, the bitrate per Hz per second for discrete levels of modulation
double *levelsPower, // in, the required power for tranmitting bits based on modulation and BER
mwSize subChannelLength, // in, number of subchannels
double *powerOfSubChannel, // out, power transmitted in each subchannel
double *rateOfSubchannel // out, rate transmitted in each subchannel
){</p><pre> double deltaPower[256]; // the difference between power of the next stage ralative to the current stage
int deltaIndex[256]; // the iindex for determining the levels of different subchannels
double temp = 0; // temparary variable
int tempIndex = 0; // temparary index
double totalRateBuffer =0; // buffer for computing the capacity provided
int n; // counter</pre><pre> // initialization
for(n = 0 ; n < subChannelLength;n++){
// computing the required power to go to the next state for each subchannel
deltaPower[n] = (levelsPower[1]-levelsPower[0])/pow(channelStateInformation[n],2);
*(powerOfSubChannel + n) = 0; // initialization
*(rateOfSubchannel + n) = 0; // initialization
*(deltaIndex + n) = 0; // initialization
};</pre><pre> // main Program plus iteration
while((totalRateBuffer < requiredRate) ){ // do it untile the required rate is satisfied</pre><pre> tempIndex = 0; // reset the temparary variables
temp = 1e4; // reset the temparary variables (choosing a very high number)</pre><pre> // sorting algorithm find the subchannel in which the required power
// is less than the other subchannel
for(n = 0 ; n < subChannelLength; n++){
if(deltaIndex[n] < numOfLevels - 1){
if(*(deltaPower + n) < temp){
temp = *(deltaPower + n);
tempIndex = n;
}
}
}
deltaIndex[tempIndex] = deltaIndex[tempIndex] + (int) 1;
// incresing the required power and rate of the selected subchannel
powerOfSubChannel[tempIndex] = *(levelsPower+deltaIndex[tempIndex]);
rateOfSubchannel[tempIndex] = *(levelsRate +deltaIndex[tempIndex]);
// next step to compute the delta power
for(n = 0 ; n < subChannelLength;n++){
if(deltaIndex[n] < numOfLevels - 1){ // excluding the subchannels with the highest level
*(deltaPower + n) = (*(levelsPower+deltaIndex[n]+1)-*(levelsPower+deltaIndex[n]))/
pow(channelStateInformation[n],2);}
else{
*(deltaPower + n) = 4e3; //choosing a very high number to exclude the subchannels with the highest level
};
}
// total rate buffer computation
totalRateBuffer = totalRateBuffer +
*(levelsRate +deltaIndex[tempIndex]) - *(levelsRate +deltaIndex[tempIndex] - 1);
};</pre><p>};</p><p>// mex function
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
// definition of parameters
double *channelStateInformation, *levelsRate, *levelsPower,requiredRate;
mwSize numOfLevels,subChannelLength;
double totalRequiredPower,*powerOfSubChannel,*rateOfSubchannel;</p><pre> // inputs extracting for C program
requiredRate = mxGetScalar(prhs[0]);</pre><pre> channelStateInformation = mxGetPr(prhs[1]);
subChannelLength = mxGetM(prhs[1]);</pre><pre> levelsRate = mxGetPr(prhs[2]);
numOfLevels = mxGetM(prhs[2]);</pre><pre> levelsPower = mxGetPr(prhs[3]);</pre><pre> // wornings in the bad definition of inputs
if (nrhs != 4)
mexErrMsgTxt("Four inputs argument required.");</pre><pre> if(nlhs > 2)
mexErrMsgTxt("Too many output arguments.");</pre><pre> if(mxGetN(prhs[0]) != 1 || mxGetN(prhs[1]) != 1 || mxGetN(prhs[2])!=1 || mxGetN(prhs[1])!=1)
mexErrMsgTxt("All inputs must be in column vector.");</pre><pre> if(mxGetM(prhs[0])>1)
mexErrMsgTxt("The first input must be scalar.");</pre><pre> if(mxGetM(prhs[2]) != mxGetM(prhs[3]))
mexErrMsgTxt("the length of the third and fourth inputs must be the same.");</pre><pre> if(subChannelLength > 256)
mexErrMsgTxt("the maximum subchannel number is 256.");</pre><pre> if(requiredRate > (double)subChannelLength*levelsRate[numOfLevels-1])
mexErrMsgTxt("the required rate cannot be supported.");</pre><pre> // outputs memory allocation
plhs[0] = mxCreateDoubleMatrix(subChannelLength ,1,mxREAL);
powerOfSubChannel = mxGetPr(plhs[0]);
plhs[1] = mxCreateDoubleMatrix(subChannelLength ,1,mxREAL);
rateOfSubchannel = mxGetPr(plhs[1]);</pre><pre> // calling the c function
greedyAlgSingleUser(
requiredRate, // in
channelStateInformation, // in
numOfLevels, // in
levelsRate, // in
levelsPower, // in
subChannelLength, // in
powerOfSubChannel, // out
rateOfSubchannel // out
);
};</pre>Prabha Kumaresanhttps://cn.mathworks.com/matlabcentral/profile/authors/3496859-prabha-kumaresantag:cn.mathworks.com,2005:Question/477572012-09-10T11:31:30Z2017-11-22T15:56:52Zfind local maxima and local minima<p>Input=my image</p><p>how to find all the points od 2D local maxima and all points of 2D local minima of input(i,j)</p><p>please help</p>Pathttps://cn.mathworks.com/matlabcentral/profile/authors/3009067-pattag:cn.mathworks.com,2005:Question/3686342017-11-22T15:55:31Z2017-11-22T15:55:31Zscatter Plot , conditional color variation based on a third value<p>I am having difficulty changing the colors in scatter plot if the condition is based on a 3rd value. For example;</p><pre class="language-matlab">f_tot = rand(3,20);
rows = 3;
x = rand(3,20);
y = rand(3,20);
hold on
box on
for p = 1: 1:rows
if f_tot >= 0.8
c = 'red';
else
c = 'blue';
end
scatter(x(:,p),y(:,p),2,c);
end
</pre><p>f_tot decision seems to be completely ignored when executing the condition</p>Zaharaddeen Hussainihttps://cn.mathworks.com/matlabcentral/profile/authors/10698816-zaharaddeen-hussainitag:cn.mathworks.com,2005:Question/3686332017-11-22T15:55:12Z2017-11-22T15:55:12Z Matlab GPU coder for Jetson TX2 <pre> I cannot run the generated project in Matlab on Jetson TX2. Someone worked with GPU coder? </pre>Vasyl Varvolikhttps://cn.mathworks.com/matlabcentral/profile/authors/10577716-vasyl-varvoliktag:cn.mathworks.com,2005:Question/3684762017-11-21T22:48:08Z2017-11-22T15:51:26ZHow to make a loop if a condition is not met<p>Hey my professor asked this question and I understand most of it except how to keep asking the user to input a valid number if the user enters 0. My code I already have is below.</p><p>In mathematics, sequences of numbers are seen regularly, many of which have defined patterns. A geometric sequence is one of the most common. In this sequence each subsequent number is calculated by multiplying the previous number by a defined ratio. This can be indicated by the equation below:</p><p>an = r*an-1</p><p>Where an indicates the nth term and r is the ratio. For example, if you have a starting value of 3 with a ratio of -2, you will get a sequence as follows:</p><p>3 -6 12 -24 48 -96 192 -384 768 -1536</p><p>You can see that each term is calculated by multiplying the previous term by -2 (the ratio), starting with the first term which is 3.</p><p>For this problem, write a script file that prompts the user to input the first term and ratio for a geometric sequence. It will then calculate the first 10 terms of the sequence and output this to the user as a vector. A geometric sequence cannot be created for a ratio or initial term of 0 so be sure to have the script produce an error if this is input and allow the user to try again and again until they input valid numbers.</p><pre> a=input('Enter the starting value: ');
r=input('Enter the ratio for the function: ');
v=zeros(1,10);
v(1)=a;
n=1;
if a~=0
if r~=0
while n<10
a=r*a;
v(n+1)=a;
n=n+1;
end
end
end
disp(v)</pre><p>Thank you, have a nice day!</p>William Taylorhttps://cn.mathworks.com/matlabcentral/profile/authors/10929697-william-taylortag:cn.mathworks.com,2005:Question/3686312017-11-22T15:49:45Z2017-11-22T15:49:45ZMatlab: Extract tiff-information about the pixelsize<p>Hi,</p><p>I have a problem: I have different tiff-pictures showing nanoparticles, which vary in their size, shape etc. So I need to measure e.g. the diameter of the nanoparticles. The tiff-picture itselve includes the information about "how long" one pixel in the picture is (e.g. AP_PIXEL_SIZE Pixel Size = 1.329 nm).
How can I extract this information from the tiff-picture withe Matlab? I do not want to look up the pixel size by myselve for every picture and I also do not want to use the ruler system to define the length.</p><p>Thank you for your help.</p>Jill Ziesmerhttps://cn.mathworks.com/matlabcentral/profile/authors/11338403-jill-ziesmertag:cn.mathworks.com,2005:Question/3685842017-11-22T12:26:16Z2017-11-22T15:55:41Zvariables values not updating in workspace<p>Hi everyone. I've been working on a code and just lately realized this weird behaviour from the script. I was always measuring a diameter of a cropped image using imshow and ginput(2), today I changed to imtool, and I noticed that using imtool was actually changing the values of 'diameter' variable, while when using imshow it wasn't. Same thing happens with the cropped image ('Crop') size!</p><p>For example, if I run my code twice using imshow and ginput(2) I get:</p><ol><li>First run: cropped image dimensions -> [200 100 3] and diameter -> 24</li><li>Second run: cropped image dimensions (this time with very different size on purpose) -> [200 100 3] and diameter (again different) -> 24</li></ol><p>Later on I launch a GUI 'guiprova' in the script and while the updated results from 'guiprova' are stored in a m.mat file, their values are updated just when I run the script another time, so all the code after launching the GUI interface becomes inconsistent!</p><p>For example:</p><ul><li>Run the code, go to GUI interface and get the variables values -> variables values are stored before ending the GUI interface and are those from the previous code run</li></ul><p>How can I solve these two problems? I know they are distinct but somehow both related to 'updating variable value' problems. I'll attach the code. Thanks!</p>giacomohttps://cn.mathworks.com/matlabcentral/profile/authors/3091880-giacomotag:cn.mathworks.com,2005:Question/3670152017-11-14T15:55:24Z2017-11-22T15:48:50ZHow to call multiple functions in ode 45?<p>I'm trying to solve 2 systems of differential equations using ode45, however I get the error code:</p><p>Error using odearguments (line 21)
When the first argument to ode45 is a function handle, the tspan argument must have at least two elements.</p><pre class="language-matlab">Error in ode45 (line 115)
odearguments(FcnHandlesUsed, solver_name, ode, tspan, y0, options, varargin);
</pre><pre class="language-matlab">Error in CBF_2006_f_v1 (line 49)
[ABP,P1,P2,xq,xm,xc,xm1,Cav] = ode45(@vsa, @aut, tspan, var0);
</pre><p>There are 2 systems: 4 equations each. The unknowns are (V_sa,P1,P2,xq,xm,xc,xm1,Cav), all the rest are parameters that have been declared at the beginning of the code.</p><p>The code main code that recalls the functions is:</p><pre class="language-matlab">%Parameter declaration .... (Rsa,V_sa_b,P_ic ...)
</pre><pre class="language-matlab">%% Diff eq system
</pre><pre> ABP= linspace(40,170,131);</pre><pre> delta=deltaCa_p;</pre><pre> for i=1:1:length(ABP)
tspan=[0 100];</pre><pre> var0=[12; 97.6; 49.67; 0; 0; 0; 0; 0.205];
[ABP,P1,P2,xq,xm,xc,xm1,Cav] = ode45(@vsa, @aut, tspan, var0);</pre><pre> end</pre><p>The 2 functions are stored in separate files and their code is:</p><pre class="language-matlab">function dvdt = vsa(ABP,var,delta,R_la,R_sa_b,V_sa_b,R_sv,P_ic,P_v,k_ven,P_v1)
</pre><pre class="language-matlab">dvdt = [(0.5*delta*(1- ((cosh(4*(var(6)+var(5)-var(4))/delta))-1)/(cosh(4*(var(6)+var(5)-var(4))) +1)))*(var(2)-P_ic) + var(8)*(( (ABP(i) -var(2))/(R_la+0.5*(R_sa_b*(V_sa_b/var(1))^2)) - (var(2)-var(3))/(R_sv+0.5*(R_sa_b*(V_sa_b/var(1))^2)) - (var(2)-P_ic)*(0.5*delta*(1- ((cosh(4*(var(6)+var(5)-var(4))/delta))-1)/(cosh(4*(var(6)+var(5)-var(4))) +1)))) /var(8)) ;
( (ABP(i) -var(2))/(R_la+0.5*(R_sa_b*(V_sa_b/var(1))^2)) - (var(2)-var(3))/(R_sv+0.5*(R_sa_b*(V_sa_b/var(1))^2)) - (var(2)-P_ic)*(0.5*delta*(1- ((cosh(4*(var(6)+var(5)-var(4))/delta))-1)/(cosh(4*(var(6)+var(5)-var(4))) +1)))) /var(8);
((var(2)-var(3))/(0.5 *(R_sa_b*(V_sa_b/var(1))^2) +R_sv)-(var(3)-P_v)/R_lv)*1/(1/(k_ven*(var(3)-P_ic-P_v1))) ;
0.5*delta*(1- ((cosh(4*(var(6)+var(5)-var(4))/delta))-1)/(cosh(4*(var(6)+var(5)-var(4))) +1))] ;
</pre><pre class="language-matlab">V_sa= var(:,1);
P1= var(:,2);
P2 = var(:,3);
Cav=var(:,8);
</pre><pre class="language-matlab">xq= var(:,4);
xc= var(:,5);
xm= var(:,6);
xm1= var(:,7);
</pre><pre class="language-matlab">dvdt=[V_sa;P1;P2;Cav; xq;xc;xm;xm1;Cav];
end
</pre><p>and</p><pre> function dxdt= aut(ABP,var,G_q,R_sa_b,V_sa_b,Pa_co2,Pa_co2_b,tau_co2,eps,u,tau2,tau1)</pre><pre> dxdt=[ (-var(4)+G_q*( ( (var(2)- var(3))/(0.5 *(R_sa_b*(V_sa_b/var(1))^2) + R_sv) ) -q_b /q_b) )/tau_q ;
(-var(5) +0.3+3*tanh(Pa_co2/Pa_co2_b -1.1))/tau_co2;
var(7);
(eps*u-tau2*var(7)-var(6))/tau1^2 ];
V_sa= var(1);
P1= var(2);
P2 = var(3);
xq= var(4);
xc= var(5);
xm= var(6);
xm1= var(7);</pre><pre> dxdt=[P1;P2;xq;xc;xm;xm1];
end</pre><p>Could you please help me find the mistakes?</p>gorilla3https://cn.mathworks.com/matlabcentral/profile/authors/8874269-gorilla3tag:cn.mathworks.com,2005:Question/3685202017-11-22T05:19:09Z2017-11-22T15:48:39Zpolyspace 2012b critical section<p>In Polyspace R2012b what is the use of critical section ?
How PS verifies it in the code?</p><p>If the critical section is called inside a wrapper will it be effective ?</p>Lenin Nelsonhttps://cn.mathworks.com/matlabcentral/profile/authors/11578591-lenin-nelsontag:cn.mathworks.com,2005:Question/3686302017-11-22T15:43:33Z2017-11-22T15:50:12ZHow to pseudo-randomize the ordering of a vector?<p>Say that I have a vector</p><pre class="language-matlab">A=randperm(10)
</pre><p>and I want to randomize the ordering of this vector. Normally I would do something like</p><pre class="language-matlab">A=Shuffle(A)
</pre><p>but in this case I want a pseudoradomized ordering: that is, the later the value is in A (ordering wise, not the actual content of the value), the more I want it to appear near the beginning of A. For instance, I want there to be a greater chance of values A(7:10) to appear near the front of A and the values A(1:4) to appear near the end of A. Hopefully that makes sense.</p><p>Is this possible to do?</p>Paul Scottihttps://cn.mathworks.com/matlabcentral/profile/authors/6004724-paul-scottitag:cn.mathworks.com,2005:Question/3685092017-11-22T04:27:36Z2017-11-22T15:42:39Zmatlab function equivalent to fit<p>Is there a function that is equivalent to the built-in function fit? Something that is simple and easy to understand how the exponential regression is calculated.</p>amateurintraininghttps://cn.mathworks.com/matlabcentral/profile/authors/10785601-amateurintrainingtag:cn.mathworks.com,2005:Question/3683152017-11-21T09:16:56Z2017-11-22T15:41:08ZMeasure simulink step time<p>Hello,
I have a problem with a slow Simulink model and want to measure each time step in order to see how long time the execution takes.
I use a fixed time step with a discrete solver and the step size is 0.01 seconds.
Does anyone know how to measure how long each time step takes, i.e. how long real time for each sample?
I tried to started digging and tested tic/toc and sim(modelname, 'Stoptime', 'simstoptime') in order to see how long the simulation takes with a fixed stop time but that only gives me the elapsed times for initialization, execution, termination and the total time. So this is not what I want to check, I want to know how long time each simulation step takes.</p>Marlo Wegenerhttps://cn.mathworks.com/matlabcentral/profile/authors/7822369-marlo-wegenertag:cn.mathworks.com,2005:Question/3685252017-11-22T06:16:39Z2017-11-22T15:40:02ZI am having an image I want to rotate by 30,45 and 90 degree<p>If I use imrotate(),it enlarges the size of the image .Without enlarging the size of the image,the image has to be rotated in 30,45 and 90 degree.How to get this?</p>Nithya SIvasamyhttps://cn.mathworks.com/matlabcentral/profile/authors/6709363-nithya-sivasamytag:cn.mathworks.com,2005:Question/3345052017-04-09T19:03:43Z2017-11-22T15:39:06ZExampleHelperRobotSimulator not working as intended. <p>I am referring to this tutorial:</p><p><a href = "https://in.mathworks.com/help/robotics/examples/mapping-with-known-poses.html">Mapping with Known poses</a></p><p>In the first step after rosinit, when the simulation is called for i.e:</p><pre class="language-matlab">sim = ExampleHelperRobotSimulator('simpleMap');
</pre><p>I get an error in MATLAB saying</p><pre> Error using ExampleHelperRobotSimulator
Too many input arguments.</pre><p>I am not understanding what exactly is the problem here. Can someone please help?
I am using R2015a version MATLAB on Ubuntu 14.04 LTS with ROS Indigo installed.</p>Srinidhi Shttps://cn.mathworks.com/matlabcentral/profile/authors/5967509-srinidhi-stag:cn.mathworks.com,2005:Question/1262672014-04-18T18:11:19Z2017-11-22T15:38:49ZHow do I count the number of zeros in a matrix?<p>I have data imported from excel into a matrix and want to count the number of zeros in the file to work out the time.</p>Franchescahttps://cn.mathworks.com/matlabcentral/profile/authors/4930210-franchescatag:cn.mathworks.com,2005:Question/3684682017-11-21T21:59:54Z2017-11-22T15:35:35ZVectorizing the colon problem<p>I need help with vectorizing this colon. I've looked at the solution presented by Loren ( <a href = "http://blogs.mathworks.com/loren/2008/10/13/vectorizing-the-notion-of-colon/">http://blogs.mathworks.com/loren/2008/10/13/vectorizing-the-notion-of-colon/</a> ), but mine is a slightly different problem and I am having trouble extending Loren's work.</p><p>Tavg, cbl, and cbu are vectors of equal but unknown length (could be anywhere from length 2 to hundreds of elements, hence the need for vectorization). T is a very long vector (~10000 elements). cbl and cbu contain the lower and upper indices of interesting regions in which the average value across that region is placed into every cell of the region (Tavg); the regions do not overlap but may touch (endpoint of reg. 1 = startpoint of reg. 2). Every region has at least length 1.</p><pre class="language-matlab">for ii = 1:length(Tavg)
T(cbl(ii):cbu(ii)) = Tavg(ii);
end
</pre>xtremecheezhttps://cn.mathworks.com/matlabcentral/profile/authors/5443689-xtremecheeztag:cn.mathworks.com,2005:Question/3685452017-11-22T08:45:18Z2017-11-22T15:32:59ZDose anyone can help with PCA technique <p>How can PCA code reduce the dimension of image, if I have image with 128*128, after used PCA to compress image?</p>Noor Abbashttps://cn.mathworks.com/matlabcentral/profile/authors/6224106-noor-abbastag:cn.mathworks.com,2005:Question/3267642017-02-24T15:44:15Z2017-11-22T15:31:11ZHow can I read a .json file?<p>Hello I found some data on the web that requires me to open a .gz file and a .json. I was able to unzip the gz file in MATLAB but have not been able to read the .json.</p><p>My Code:</p><pre class="language-matlab">>> fname = 'meta_Electronics.json';
>> fid = fopen(fname);
>> raw = fread(fid,inf);
>> str = char(raw');
>> fclose(fid);
>> data = JSON.parse(str)
</pre><p>and this is the error that is displayed:</p><pre class="language-matlab">Undefined variable "JSON" or class "JSON.parse".
</pre><p>Can someone point me in the right direction, as far as what i need to change?</p><p>Cheers.</p>Carlyle Hickmanhttps://cn.mathworks.com/matlabcentral/profile/authors/8375313-carlyle-hickmantag:cn.mathworks.com,2005:Question/3686282017-11-22T15:30:29Z2017-11-22T15:30:29ZCan you say what is the problem ?<p>>> install_addon('smlink.r2016a.win64.zip')
Installing smlink...
Extracting archive smlink.r2016a.win64.zip to C:\Program Files\MATLAB\R2016a...
Error using install_addon (line 53)
Access is denied.</p>Ferzin Zeynallihttps://cn.mathworks.com/matlabcentral/profile/authors/11561648-ferzin-zeynallitag:cn.mathworks.com,2005:Question/3685542017-11-22T09:34:50Z2017-11-22T15:30:17ZContour plot with a circular boundary<p>I have a circular object which I sampled at nine locations and got some data. Now, I'd like to create a contour plot of the data but I do not know how to create one with a circular boundary.</p><p>I've managed to create a graph with the following code:</p><pre class="language-matlab">% Coordinates of data points and data.
testX = [100,0,-100,0,0,50,0,-50,0];
testY = [0,-100,0,100,0,0,-50,0,50];
testZ = [58.4542,51.5161,52.1838,55.8480,54.5418,51.9043,48.3288,47.7176,58.3356];
</pre><pre class="language-matlab">% Put the data to right format.
n=5;
[X,Y] = meshgrid(linspace(min(testX),max(testX),n), linspace(min(testY),max(testY),n));
Z = griddata(testX,testY,testZ,X,Y);
</pre><pre class="language-matlab">% Plot a graph.
figure
contourf(X,Y,Z,30,'LineColor', 'none');
daspect([1 1 1])
% Colormap
c = hsv;
c = c(1:45,:);
colormap(c);
</pre><p>Which produces:</p><img src = "/matlabcentral/answers/uploaded_files/95651/untitled.png"><p>But I'd like to get a graph where the boundary is circular, similar to this one hastily created in Origin:</p><img src = "/matlabcentral/answers/uploaded_files/95653/Graph1.png"><p>I tried the following, but it's not quite right.</p><pre class="language-matlab">% Coordinates of data points and data.
testX = [100,0,-100,0,0,50,0,-50,0];
testY = [0,-100,0,100,0,0,-50,0,50];
testZ = [58.4542,51.5161,52.1838,55.8480,54.5418,51.9043,48.3288,47.7176,58.3356];
</pre><pre class="language-matlab">radius = 100;
decimals = 4;
% Create polar data
[r,t] = meshgrid(-radius:1:radius,0:pi/30:(2*pi));
% Convert to Cartesian
X = round(r.*cos(t),decimals);
Y = round(r.*sin(t),decimals);
</pre><pre class="language-matlab">Z = griddata(testX,testY,testZ,X,Y);
</pre><pre class="language-matlab">% Plot a graph.
figure
contourf(X,Y,Z,30,'LineColor', 'none');
daspect([1 1 1])
% Colormap
c = hsv;
c = c(1:45,:);
colormap(c);
</pre><img src = "/matlabcentral/answers/uploaded_files/95654/untitled2.png"><p>Any help would be appreciated, thanks in advance.</p>tmuhttps://cn.mathworks.com/matlabcentral/profile/authors/10571290-tmutag:cn.mathworks.com,2005:Question/3686272017-11-22T15:29:26Z2017-11-22T15:29:26ZForcing ownership of subsystem data to its self within a simulink model<p>Hi all,</p><p>I have a bunch of matlab functions encapsulated in Simulink Matlab function blocks.
These Matlab function blocks are part of a Simulink library.</p><p>I am code generating groups of these functions. Function packaging is set as reusable and file name is set to user specified so as to force groups of these functions to code generate as a subsystem (module).</p><p>I am using Simulink.Bus (structure) data types, placed in the Base workspace, set up as "Storage Class: Exported" and "HeaderFile: SubSystemName_types.h".
I am using Simulink.Parameters set up as "Storage Class: Volatile(Custom)" and "Owner: SubSystemName" to try and force the subsystem to own its data.</p><p>This is not working and ownership of the subsystem data is with the model instead of the subsystem (module).
I am running out of ideas in how to solve this.</p><p>Should I be using mpt.Parameters instead of Simulink.Parameters?
Should I use a referenced model approach instead of simulink library approach?
I am using Matlab 2016b.</p><p>Thanks
Alex</p>Alex Bogiashttps://cn.mathworks.com/matlabcentral/profile/authors/6820168-alex-bogias