https://ch.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2019-07-17T00:19:47Ztag:ch.mathworks.com,2005:Question/4720452019-07-16T23:30:29Z2019-07-17T00:19:47Zsolve a system of equations symbolically with R2018a>> eqn1='(Fa0*x1)/0.1*(9.05*(1-x1))*(27.8-9.05*x1))==3785'
eqn1 =
'(Fa0*x1)/0.1*(9.05*(1-x1))*(27.8-9.05*x1))==3785'
>> eqn2='(Fa0*(x2-x1))/0.1*(9.05*(1-x2))*(27.8-9.05*x2))==3785'
eqn2 =
'(Fa0*(x2-x1))/0.1*(9.05*(1-x2))*(27.8-9.05*x2))==3785'
>> eqn3='(Fa0*(0.95-x2))/0.1*(9.05*(1-0.95))*(27.8-9.05*0.95))==3785'
eqn3 =
'(Fa0*(0.95-x2))/0.1*(9.05*(1-0.95))*(27.8-9.05*0.95))==3785'
>> solT=solve(eqn1,eqn2,eqn3,x1,x2,Fa0)
Error using solve>getEqns (line 418)
List of equations must not be empty.
Error in solve (line 226)
[eqns,vars,options] = getEqns(varargin{:});Katy Skillingshttps://ch.mathworks.com/matlabcentral/profile/authors/11882563-katy-skillingstag:ch.mathworks.com,2005:Question/4720472019-07-17T00:10:29Z2019-07-17T00:10:29ZCan i call variable of another m file in GUI ?Hello everyone,
i am designing a GUI for bellhop acoustic Toolbox, I m begineer in GUI designing. I had write a program that can take few parameters as a input from user and run bellhop acoustic tool. I am wondering can i call variable of the another m file to GUI ? for example. If i want to take frequency as input parameter from user and put that user input frequency value to another m file and run bellhop when i press RunBellhop button ?
I am not sure how can i bind the variable of another m file to GUI ? Here I attach a screenshot of GUI and rough m file of GUI.
P.S. I am taking frequency input from user(GUI), writing that to another .m file and when i click on Run Bellhop button it should run below code
%=====================%
% Run Bellhop %
%=====================%
wbellhopenvfil('munkp',case_title,source_data,surface_data,ssp_data,bottom_data,options);
bellhop munkp
and plot the output in space provided :
%=====================%
% Reading output %
%=====================%
figure(2)
subplot(2,1,1)
counter = counter + 1 ; figure(counter)
plot( c , depths ), box on, grid on, view(0,-90)
xlabel('Sound speen (m/s)')
ylabel('Depth (m)')
title('Supply profile to bellhop')
subplot(2,1,2)
switch output_option
case '''C'''
plotshd( 'munkp.shd' ), box on, hold on
plot(rati, zati)
plot(rbty,zbty)
%plotssp( 'munkp' )
hold off
case '''E'''
plotray( 'munkp' ), box on, hold on
plot(rati, zati)
plot(rbty,zbty)
hold off
case '''R'''
plotray( 'munkp' ), box on, hold on
plot(rati, zati)
plot(rbty,zbty)
hold off
case '''IB'''
plotshd( 'munkp.shd' ), box on, hold on
plot(rati, zati)
plot(rbty,zbty)
%plotssp( 'munkp' )
hold off
otherwise
disp('Unknown output option.')
end
disp('done.')
Thanks in advance.
bellhopGUI.m
function varargout = BellhopGUI(varargin)
% BELLHOPGUI MATLAB code for BellhopGUI.fig
% BELLHOPGUI, by itself, creates a new BELLHOPGUI or raises the existing
% singleton*.
%
% H = BELLHOPGUI returns the handle to a new BELLHOPGUI or the handle to
% the existing singleton*.
%
% BELLHOPGUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in BELLHOPGUI.M with the given input arguments.
%
% BELLHOPGUI('Property','Value',...) creates a new BELLHOPGUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before BellhopGUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to BellhopGUI_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help BellhopGUI
% Last Modified by GUIDE v2.5 16-Jul-2019 20:23:42
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @BellhopGUI_OpeningFcn, ...
'gui_OutputFcn', @BellhopGUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before BellhopGUI is made visible.
function BellhopGUI_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to BellhopGUI (see VARARGIN)
% Choose default command line output for BellhopGUI
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes BellhopGUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = BellhopGUI_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function ns_Callback(hObject, eventdata, handles)
% hObject handle to ns (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of ns as text
% str2double(get(hObject,'String')) returns contents of ns as a double
% --- Executes during object creation, after setting all properties.
function ns_CreateFcn(hObject, eventdata, handles)
% hObject handle to ns (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function sa_Callback(hObject, eventdata, handles)
% hObject handle to sa (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of sa as text
% str2double(get(hObject,'String')) returns contents of sa as a double
% --- Executes during object creation, after setting all properties.
function sa_CreateFcn(hObject, eventdata, handles)
% hObject handle to sa (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function freq_Callback(hObject, eventdata, handles)
% hObject handle to freq (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of freq as text
% str2double(get(hObject,'String')) returns contents of freq as a double
%store the contents of input1_editText as a string. if the string
%is not a number then input will be empty
input = str2num(get(hObject,'String'));
%checks to see if input is empty. if so, default input1_editText to zero
if (isempty(input))
set(hObject,'String','0')
end
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function freq_CreateFcn(hObject, eventdata, handles)
% hObject handle to freq (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function rr1_Callback(hObject, eventdata, handles)
% hObject handle to rr1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of rr1 as text
% str2double(get(hObject,'String')) returns contents of rr1 as a double
% --- Executes during object creation, after setting all properties.
function rr1_CreateFcn(hObject, eventdata, handles)
% hObject handle to rr1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function nrd_Callback(hObject, eventdata, handles)
% hObject handle to nrd (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of nrd as text
% str2double(get(hObject,'String')) returns contents of nrd as a double
% --- Executes during object creation, after setting all properties.
function nrd_CreateFcn(hObject, eventdata, handles)
% hObject handle to nrd (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function nrr_Callback(hObject, eventdata, handles)
% hObject handle to nrr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of nrr as text
% str2double(get(hObject,'String')) returns contents of nrr as a double
% --- Executes during object creation, after setting all properties.
function nrr_CreateFcn(hObject, eventdata, handles)
% hObject handle to nrr (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function zr1_Callback(hObject, eventdata, handles)
% hObject handle to zr1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of zr1 as text
% str2double(get(hObject,'String')) returns contents of zr1 as a double
% --- Executes during object creation, after setting all properties.
function zr1_CreateFcn(hObject, eventdata, handles)
% hObject handle to zr1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function nb_Callback(hObject, eventdata, handles)
% hObject handle to nb (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of nb as text
% str2double(get(hObject,'String')) returns contents of nb as a double
% --- Executes during object creation, after setting all properties.
function nb_CreateFcn(hObject, eventdata, handles)
% hObject handle to nb (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in bellhop.
function bellhop_Callback(hObject, eventdata, handles)
% hObject handle to bellhop (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
function rr2_Callback(hObject, eventdata, handles)
% hObject handle to rr2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of rr2 as text
% str2double(get(hObject,'String')) returns contents of rr2 as a double
% --- Executes during object creation, after setting all properties.
function rr2_CreateFcn(hObject, eventdata, handles)
% hObject handle to rr2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function zr2_Callback(hObject, eventdata, handles)
% hObject handle to zr2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of zr2 as text
% str2double(get(hObject,'String')) returns contents of zr2 as a double
% --- Executes during object creation, after setting all properties.
function zr2_CreateFcn(hObject, eventdata, handles)
% hObject handle to zr2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function zs_Callback(hObject, eventdata, handles)
% hObject handle to zs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of zs as text
% str2double(get(hObject,'String')) returns contents of zs as a double
% --- Executes during object creation, after setting all properties.
function zs_CreateFcn(hObject, eventdata, handles)
% hObject handle to zs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
Jay Patelhttps://ch.mathworks.com/matlabcentral/profile/authors/12375309-jay-pateltag:ch.mathworks.com,2005:Question/4718202019-07-15T19:12:39Z2019-07-16T23:54:25ZI have discovered that in solving ordinary differential equations things can get very easy if we use micro-intervals (intervals divided by 10 000 or more) and very rough methods like Euler's , to get the same accuracy as when using complex methods. ODEs of any order with initial conditions can be solved easely "using micro-intervals (intervals divide by more than a 1000) associated with Euler's method - definition of derivative -, can lead to great accuracy. I have a batch of scripts that can prove that. (study1, study2 ......). The simplicity is the great asset. Is this known ?Carlos Steinstrasserhttps://ch.mathworks.com/matlabcentral/profile/authors/1967874-carlos-steinstrassertag:ch.mathworks.com,2005:Question/4720442019-07-16T23:14:40Z2019-07-16T23:52:59ZUse different colormaps for pcolor subplotsHi! I'm trying to plot two subplot with different color scales. I finally made the colorbars the correct colors but now my data is using an entirely different colormat. Does anyone know how to fix this so the data is still shown with the jet colors (low=red for subplot 1 and low=blue for subplot 2)? Thank you in advance!
This is my code for the first two subplots:
ax(1) = subplot(4,1,1)
plot(MX,PK.PRESS(9,:),'color',[.8 .8 .8]);
hold on
pcolor(MX,PK.mab,PK.fixPH);
shading('interp');
ylabel('Depth (mab)','fontsize',16);
c=colorbar; colormap(c,flipud(jet)) %color scale should be flipped!
set(c, 'Position', [0.93 .76 .015 .15])
title(c,'pH','fontsize',16);
% ylim([0 6.1])
set(gca,'fontsize',14);
title('PK Mooring')
x = datenum('June-4-2018'):7:datenum('Oct-8-2018');
set(gca, 'XTick', x);
datetick('x','mm/dd','keepticks')
ax(2) = subplot(4,1,2)
pcolor(MX,PK.mab,PK.TEMP); %temperature
% shading('interp');
shading('flat');
ylabel('Depth (mab)','fontsize',20);
d=colorbar; colormap(d,jet);
caxis([9 19.2]);
title(d,'T (\circC)','fontsize',18);
set(d, 'Position', [0.93 .54 .015 .15]) %Set position as [left, bottom, width, height] %this is right middle
set(gca,'fontsize',14);
% title('PK Temperature')
x = datenum('June-4-2018'):7:datenum('Oct-8-2018');
set(gca, 'XTick', x);
datetick('x','mm/dd','keepticks');
Heidi Hirshhttps://ch.mathworks.com/matlabcentral/profile/authors/6143971-heidi-hirshtag:ch.mathworks.com,2005:Question/4720432019-07-16T23:13:40Z2019-07-16T23:47:10ZData import from csv fileI want to import data from my csv file which has more than 2 million rows. I cant open the file in csv format. Thus, I want to open this in matlab and do the operations. I have used x= importdata('filename.csv') but this does not work.Harsh Robhttps://ch.mathworks.com/matlabcentral/profile/authors/15148505-harsh-robtag:ch.mathworks.com,2005:Question/4720462019-07-16T23:46:36Z2019-07-16T23:46:36ZIs there a size limitation to converting 3D array from C# to MWNumericArray?I have a c# application that needs to send some data to Matlab. The data is a 3D array of shorts.
My c# Conversion method looks like so:
public static MWArray ShortArrayToMWArray(short[,,] intArray, int v, int v1, int v2)
{
try
{
//MWArray MW = new MWNumericArray(intArray);
//return MW;
MWNumericArray matrix = null;
matrix = new MWNumericArray(MWArrayComplexity.Real, MWNumericType.Int8, v, v1, v2);
matrix = intArray;
return matrix;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return new MWNumericArray();
}
}
My array is: {short[532, 512, 512]}. When I send in the whole thing, I get a very bizarre error message:
It's only when I started to play with the sizes that I started to doubt and ask this question. If I send in 1/4 of the array, it does the conversion (1/2 is still the same error):
// Copy 1/4 of the array into a tmp array
Array tmpArray = Array.CreateInstance(typeof(short), originalArray.GetLength(0)/4, originalArray.GetLength(1)/4, originalArray.GetLength(2)/4);
System.Array.Copy(voxelArray, tmpArray, originalArray.GetLength(0)/4 * originalArray.GetLength(1)/4 * originalArray.GetLength(2)/4);
MWArray mwVol = MatlabUtils.ShortArrayToMWArray((short[,,])tmpArray, originalArray.GetLength(0) / 4, originalArray.GetLength(1) / 4, originalArray.GetLength(2) / 4);
I'm guessing I'm doing the conversion wrong, but not sure.
ThanksOfir Magenhttps://ch.mathworks.com/matlabcentral/profile/authors/15332743-ofir-magentag:ch.mathworks.com,2005:Question/4700952019-07-03T14:58:27Z2019-07-16T23:42:59ZHow to solve a special linear equation Ax=b? A is a row vector. Dear All,
I am trying to solve the following linear equation Ax=b:
[a1 a2 ... an][x1 x2 ... xn]' = b. where b is a complex number, a_i is also complex, and x_i is 1 or 0. This equation is unsolvable because the number of variables is n while the equation is 1. But if we add another condition: x is the sparse solution (number of nonzero entries is known) , there exists a unique solution.
For example, [0.1+0.2i 0.2+0.3i 0.4+0.5i 0.6+7i 0.8+0.9i]*[x1 x2 x3 x4 x5 x6 x7 x8 x9]' = 0.5+0.7i. If we know there are 2 non-zeros in x, then we got a unique solution x1=x3=1, others are zero.
But would someone tell me how to solve this equation using Matlab code?
Thanks a lot.
BensonBenson Gouhttps://ch.mathworks.com/matlabcentral/profile/authors/4652929-benson-goutag:ch.mathworks.com,2005:Question/4720342019-07-16T21:41:30Z2019-07-16T23:39:49ZHow can I get the index numbers of cells that form a specific string?I have a column of strings as follows:
Ex1:
str=[{'a.b.c.d'};{'b.c.d.e'};{'a'};{'b'};{'c'};{'d'};{'e'}];
Ex2:
str=[{'a.b'};{'b.c'};{'c.d'};{'d.e'};{'a.b.c'};{'b.c.d'};{'c.d.e'}];
I want to return the index of cells that can form 'a.b.c.d.e'.
In example 1, rows 1&7, 3&2, and 3&4&5&6&7 can form 'a.b.c.d.e'; hence I want the code to return [(1,7);(3,2);(3,4,5,6,7)] (in however format).
In example 2, rows 1&7 and 5&4 can form 'a.b.c.d.e'; hence I want the code to return [(1,7);(5,4)].
Can anyone help me on how to do this? I'm quite new at Matlab and none of my ideas seem to lead anywhere at this point.Elif Osunhttps://ch.mathworks.com/matlabcentral/profile/authors/15631754-elif-osuntag:ch.mathworks.com,2005:Question/4719712019-07-16T14:59:15Z2019-07-16T23:39:25ZExcluding peaks of frequency plot in findpeaks()Hello everyone, I am analysing a (recorded) periodic signal. On the Aplitude-Frequency plot, there are some distinctive peaks but because of noise (I believe), there are some "random" frequencies, that present high amplitudes, sometimes higher than the desired frequency's peaks. I have used findpeaks, but could not produce the optimum results:
%% ________________________________________________________Input
[y, Fs] = audioread('A3.wav');
t=linspace(0,length(y)/Fs, length(y));
Fn = Fs/2;
%% ______________________________________________Noise Canceling
Wp = 1000/Fn;
Ws = 1100/Fn;
Rp = 1;
Rs = 150;
[n,Ws] = cheb2ord(Wp,Ws,Rp,Rs);
[z,p,k] = cheby2(n,Rs,Ws,'low');
[soslp,glp] = zp2sos(z,p,k);
freqz(soslp, 2^16, Fs);
Yclean = filtfilt(soslp, glp, y);
%% __________________________________________________________DFT
L=length(Yclean);
Ydft = fft(Yclean);
F = Fs*(0:(L/2))/L;
DFTphase2 = abs(Ydft/L);
DFTphase1 = DFTphase2(1:L/2+1);
DFTphase1(2:end-1) = 2*DFTphase1(2:end-1);
figure;
subplot(2,1,1);
plot(F,DFTphase1);
title('DFT - Amplitude Spectrum of Signal');
xlabel('Frequency (Hz)');
ylabel('Absolute Amplitude of Frequencies');
xlim([0 20000]);
%________________________________________________Focus
idx = F >= 0 & F <= 1000; %Focusing 0-1000 Hz
DFTzoomX = F(idx);
DFTzoomY = DFTphase1(idx);
subplot(2,1,2);
plot(DFTzoomX, DFTzoomY);
title('DFT - Amplitude Spectrum of Signal');
xlabel('Frequency (Hz)');
ylabel('Absolute Amplitude of Frequencies');
[DFTpks1,DFTlocs1] = findpeaks(DFTzoomY, 'MinPeakProminence',0.002685, 'MinPeakDistance',115);
hold on
ylv = ylim;
plot([1;1]*DFTzoomX(DFTlocs1), ylv(:)*ones(size(DFTpks1')))
hold off
With a period of around 130 Hz, I would like to only keep the lines corresponding to the products of this frequency.
Plot attached below and if needed ask me for more of the code.
Thank you very much in advance!Petros Tsitourashttps://ch.mathworks.com/matlabcentral/profile/authors/15609763-petros-tsitourastag:ch.mathworks.com,2005:Question/4720372019-07-16T21:59:51Z2019-07-16T23:12:01ZIssue Saving image with text overlay to pngI am having issues saving an image that has been displayed in a figure, with a couple markers plotted at specific coordinates and then text overlaid using the text function. I am trying to safe this off as a png via saveas(gcf,'filename.png'); and the figure exports but the overlaid text is missing. The title and the marker points I plotted show up but no text. Below is the figure.
Attached is the exported png using saveas
My code looks as follows:
figure; imshow(img,[]);
hold on;
plot(Stats(TestNum).Centroid(1),Stats(TestNum).Centroid(2),'b*');
set(gca, 'ActivePositionProperty', 'OuterPosition');
[filepath,name,ext] = fileparts(files(TestNum).name);
title({[];name;['Original Image With Centroid Marked']},'FontSize',FontSize);
text(20,500,{['Area = ',num2str(Stats(TestNum).Area.*pixel_scale^2,'%3.2f'),'mm^2'];...
['Eccentricity = ',num2str(Stats(TestNum).Eccentricity,'%3.2f')];...
['Orientation = ',num2str(Stats(TestNum).Orientation,'%3.2f'),char(176)];...
['Major Axis Length = ',num2str(Stats(TestNum).MajorAxisLength.*pixel_scale,'%3.2f'),'mm'];...
['Minor Axis Length = ',num2str(Stats(TestNum).MinorAxisLength.*pixel_scale,'%3.2f'),'mm']},...
'Color','white','FontSize',FontSize);
saveas(gcf,[pwd '\output\Test ',num2str(TestNum),'\TubeMidpointCrossSection - Test ',num2str(TestNum),'.png']);
Erick Oberstarhttps://ch.mathworks.com/matlabcentral/profile/authors/2291488-erick-oberstartag:ch.mathworks.com,2005:Question/4716812019-07-14T22:45:53Z2019-07-16T23:00:21Zarea of many cracks in imagehello
i am ask about how can find the objects in image
type of image: street image that contine crack
i need to find the crack and compute the area of each crack in image and then get Priority to the crack have big areaNida Aleqabiehttps://ch.mathworks.com/matlabcentral/profile/authors/14383694-nida-aleqabietag:ch.mathworks.com,2005:Question/4720422019-07-16T22:59:46Z2019-07-16T22:59:46ZIs it possible to plot real radar output in Simulink's bird's eye plot?I have a Continental radar and want to plot output from this radar in bird's eye plot. I am successfully able to do this using Matlab's bep plot and by feeding in radar's CAN log. Now, I want to do the same in Simulink but in real-time. That is, I want to feed in data from Radar into simulink and simultaneously visualize data in a birds eye view.
PS: I tried to use the bird's eye view plot in simulink but it looks like it expects simulink blocks like Scenario reader and Radar detection generator which are used for simulating radar inputs. The question is if I can do this by inputting actual radar data than a simulation.Sujith Josehttps://ch.mathworks.com/matlabcentral/profile/authors/15658443-sujith-josetag:ch.mathworks.com,2005:Question/4720322019-07-16T21:34:30Z2019-07-16T22:45:35ZHow do I extract a 256x256 matrix from a 1x1 cell?
Using an augmented image datastore, I reading a single image and the output looks like this. When I use the table2cell function, the new image has a strange output and not the matrix I was expecting (only 1x1!). How do I produce the 256x256 matrix of values that I am looking for?Seton Liuhttps://ch.mathworks.com/matlabcentral/profile/authors/15584633-seton-liutag:ch.mathworks.com,2005:Question/4716612019-07-14T17:25:49Z2019-07-16T22:44:23ZHow to plot LSQCURVEFIT output I have almost finished writing a program that fits my data using lsqcurvefit and two different functions for different parts of the data. The only part remaining is plotting the fit (output) from the lsqcurvefit run. I have attached my code and some sample data. I tried using linspace and line functions to do the plot, but I get 'vectors must be the same length'. Data.m is the file to run. GlobChiSq.m has the two model functions. caclPinf.m, calcLambda.m, and calcD.m are used by GlobChiSq.m. The sample data: concentration.txt, current-washin-washout-100-cat.txt, time-washin-washout-100-cat.txt, and traceLength.txt should be imported as column vectors and transposed to row vectors, and the variables should be named concentration, current, time, and traceLength respectively. Could someone help me figure out the plotting? Data.m is where I try to plot lsqcurvefit result. I'm not sure what, exactly, should go in linspace and line to plot the curve fit result. Thanks!
Note: The current and time data files are too big to attach here. I can send them to the person that helps with this question. Just let me know how to send it to you.Kelly McGuirehttps://ch.mathworks.com/matlabcentral/profile/authors/2733866-kelly-mcguiretag:ch.mathworks.com,2005:Question/4718512019-07-16T04:36:33Z2019-07-16T22:40:44ZHow to change the working directory as code progresses...Hi all, I have two functions that I would like to run on a folder of files.
The first 'GetFrames(x)' takes a folder of .avi files (specified by path 'x') and outputs them in a new folder within x called 'Frames'.
I then use a second function called 'AddGrids(x)' on these files (x=x/Frames), and produce a new folder within x called 'FramesWithGrids'.
My problem is that for this to work, I need to run the first function, wait until the Frames folder is created, and copy the 'AddGrids.m' file into the new folder before I can run the second function.
I feel like there should be a way to do this without having to copy the .m file manually. I thought it would work by changing the directory but it does not.
Thanks in advance for any suggestions you can offer!
Louise
x='C:\Users\lwil634\Documents\Cameras\practice' %folder where .avi files are
GetFrames(x);
%once this runs we have created Frames folder which contains files we want
%to run next function on, but have to stay in x where .m files are.
b=strcat(x, '\Frames');
cd(b);
AddGrids(b)
%If I copy AddGrids.m into Frames folder the function works and creates the
%next subfolder inside the Frames folder.
AddGrids('C:\Users\lwil634\Documents\Cameras\practice\Frames')Louise Wilsonhttps://ch.mathworks.com/matlabcentral/profile/authors/14092323-louise-wilsontag:ch.mathworks.com,2005:Question/4720412019-07-16T22:38:50Z2019-07-16T22:38:50Zproblem finding the coordinates of point in stainer tree problem by brute force hi
what's wrong with the coding. i want to find the value of 'a' and 'b' for which 'L' is minimum.
>> [m,a,b]=min_length(10:.01:40,5:.01:25)
m =45.7813
a = 40
b = 25
these are not the correct value of 'a' and 'b'.
thank you.jakaria babarhttps://ch.mathworks.com/matlabcentral/profile/authors/11609235-jakaria-babartag:ch.mathworks.com,2005:Question/4564102019-04-15T08:31:43Z2019-07-16T22:38:13ZMex compiling error 'g++: error: libmwlapack.lib: No such file or directory'Hello,
I'm currently using Matlab R2019a with Mingw64 compiler.
The follwing code is a part of "SuiteSparse" installation.
s= 'mex -silent -largeArrayDims -DBLAS64 -O -DNPARTITION -DNMATRIXOPS -DNMODIFY -I. -I../../AMD/Include -I../../COLAMD/Include -I../../CHOLMOD/Include -I../Include -I../../SuiteSparse_config -I../../CHOLMOD/MATLAB/Windows spqr.cpp spqr_parallel.obj spqr_1colamd.obj spqr_1factor.obj spqr_1fixed.obj spqr_analyze.obj spqr_append.obj spqr_assemble.obj spqr_cpack.obj spqr_csize.obj spqr_cumsum.obj spqr_debug.obj spqr_factorize.obj spqr_fcsize.obj spqr_freefac.obj spqr_freenum.obj spqr_freesym.obj spqr_front.obj spqr_fsize.obj spqr_happly.obj spqr_happly_work.obj spqr_hpinv.obj spqr_kernel.obj spqr_larftb.obj spqr_panel.obj spqr_rconvert.obj spqr_rcount.obj spqr_rhpack.obj spqr_rmap.obj spqr_rsolve.obj spqr_shift.obj spqr_stranspose1.obj spqr_stranspose2.obj spqr_trapezoidal.obj spqr_type.obj spqr_tol.obj spqr_maxcolnorm.obj SuiteSparseQR_qmult.obj SuiteSparseQR.obj SuiteSparseQR_expert.obj spqr_mx.obj SuiteSparse_config.obj amd_1.obj amd_2.obj amd_aat.obj amd_control.obj amd_defaults.obj amd_dump.obj amd_global.obj amd_info.obj amd_order.obj amd_postorder.obj amd_post_tree.obj amd_preprocess.obj amd_valid.obj colamd.obj cholmod_aat.obj cholmod_add.obj cholmod_band.obj cholmod_change_factor.obj cholmod_common.obj cholmod_complex.obj cholmod_copy.obj cholmod_dense.obj cholmod_error.obj cholmod_factor.obj cholmod_memory.obj cholmod_sparse.obj cholmod_transpose.obj cholmod_triplet.obj cholmod_check.obj cholmod_read.obj cholmod_write.obj cholmod_amd.obj cholmod_analyze.obj cholmod_colamd.obj cholmod_etree.obj cholmod_factorize.obj cholmod_postorder.obj cholmod_rcond.obj cholmod_resymbol.obj cholmod_rowcolcounts.obj cholmod_rowfac.obj cholmod_solve.obj cholmod_spsolve.obj cholmod_super_numeric.obj cholmod_super_solve.obj cholmod_super_symbolic.obj rand48.obj spqr_mx_error.obj libmwlapack.lib libmwblas.lib'
eval(s)
yields the error message :
Error using mex
g++: error: libmwlapack.lib: No such file or directory
g++: error: libmwblas.lib: No such file or directory
I can find the above lib files at ....\MATLAB\R2019a\extern\lib\win64\mingw64
Why i got such error message?? Any helps would be appreciated. KiChang Leehttps://ch.mathworks.com/matlabcentral/profile/authors/594538-kichang-leetag:ch.mathworks.com,2005:Question/4720392019-07-16T22:12:48Z2019-07-16T22:35:34Zchange variable when difference between 2 rows I have a variable matrix, one column is datetime, I want to change a variable called lastdayclose to the previous days close price.
eg: matrix has 2 columns
datetime
close price
variable lastdaysclose:
so I want to loop through the array and pickup the close of yesterday and assign it to the variable lastdaysclose each time there is a new day:James Uptonhttps://ch.mathworks.com/matlabcentral/profile/authors/5110937-james-uptontag:ch.mathworks.com,2005:Question/103282011-06-27T08:43:45Z2019-07-16T22:33:48Zhow to plot function with a sine input in Matlab (not in simulink)we just type command 'step(function)' to plot a function with input step but How to plot a function that use sine as an input in Matlab.
Lokman Abdullahhttps://ch.mathworks.com/matlabcentral/profile/authors/2721114-lokman-abdullahtag:ch.mathworks.com,2005:Question/4720382019-07-16T22:07:38Z2019-07-16T22:33:41Zconvert from datetimes to doubleI have created a variable called P_D and I want to put into it a date time asociated with each row (its financial data)
P_D(i,1)=data.Dates(i);
P_D(i,2)=data.Close(i);
P_D(i,3)=Premium;
When I run the code it is saying:
The following error occurred converting from datetime to double:
Undefined function 'double' for input arguments of type 'datetime'. To convert from datetimes to numeric, first subtract off a
datetime origin, then convert to numeric using the SECONDS, MINUTES, HOURS, DAYS, or YEARS functions.
Error in test2 (line 38)
P_D(i,1)=data.Dates(i);
How do I convert to numeric? '09-Jul-2019 02:25:00'
James Uptonhttps://ch.mathworks.com/matlabcentral/profile/authors/5110937-james-uptontag:ch.mathworks.com,2005:Question/2313642015-07-27T18:18:52Z2019-07-16T22:32:11ZMethod of Newton Rhapson if true
% code
end a program on the Newton Rhapson method in GUI.
if true
function varargout = untitled(varargin)
% UNTITLED M-file for untitled.fig
% UNTITLED, by itself, creates a new UNTITLED or raises the existing
% singleton*.
%
% H = UNTITLED returns the handle to a new UNTITLED or the handle to
% the existing singleton*.
%
% UNTITLED('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in UNTITLED.M with the given input arguments.
%
% UNTITLED('Property','Value',...) creates a new UNTITLED or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before untitled_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to untitled_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help untitled
% Last Modified by GUIDE v2.5 27-Jul-2015 13:52:31
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @untitled_OpeningFcn, ...
'gui_OutputFcn', @untitled_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before untitled is made visible.
function untitled_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to untitled (see VARARGIN)
% Choose default command line output for untitled
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes untitled wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = untitled_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
function xini_Callback(hObject, eventdata, handles)
% hObject handle to xini (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of xini as text
% str2double(get(hObject,'String')) returns contents of xini as a double
% --- Executes during object creation, after setting all properties.
function xini_CreateFcn(hObject, eventdata, handles)
% hObject handle to xini (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function tolerancia_Callback(hObject, eventdata, handles)
% hObject handle to tolerancia (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of tolerancia as text
% str2double(get(hObject,'String')) returns contents of tolerancia as a double
% --- Executes during object creation, after setting all properties.
function tolerancia_CreateFcn(hObject, eventdata, handles)
% hObject handle to tolerancia (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function funcion_Callback(hObject, eventdata, handles)
% hObject handle to funcion (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of funcion as text
% str2double(get(hObject,'String')) returns contents of funcion as a double
% --- Executes during object creation, after setting all properties.
function funcion_CreateFcn(hObject, eventdata, handles)
% hObject handle to funcion (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function raiz_Callback(hObject, eventdata, handles)
% hObject handle to raiz (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of raiz as text
% str2double(get(hObject,'String')) returns contents of raiz as a double
% --- Executes during object creation, after setting all properties.
function raiz_CreateFcn(hObject, eventdata, handles)
% hObject handle to raiz (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on selection change in seleccionar.
function seleccionar_Callback(hObject, eventdata, handles)
% hObject handle to seleccionar (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
format long g
f=get(handles.funcion,'string');
xi=get(handles.xini,'string');
Es=get(handles.tolerancia,'string');
xi=str2double(xi);
Es=str2double(Es);
syms x
df=diff(f);
df=inline('df');
ddf=diff(f,2);
ddf=inline('ddf');
f=inline(f);
i=1;
Ea(1)=100;
xi1=x1;
v=get(handles.seleccionar,'value');
switch v
case 2
while abs(Ea>=Es)
fxi=feval(f,xi);
dfxi=feval(df,xi);
xi1= xi -(fxi/dfxi);
Ea=abs((xi1-xi)/(xi1)*100);
xi=xi1;
i=i+1;
end
h=num2str(xi1);
set(handles.raiz,'string',h);
c=str3double(h);
fplot(handles.grafica,f,[(c-5) (c+5)]);
case 3
while abs(Ea>=Es)
fxi=feval(f,xi);
dfxi=feval(df,xi);
ddfxi=feval(ddf,xi);
xi1= xi -((fxi*dfxi)/((dfxi)^2-fxi*ddfxi));
Ea=abs(((xi1-xi)/xi1)*100);
xi=xi1;
i=i+1;
end
h=num2str(xi1);
set(handles.raiz,'string',h);
c=str3double(h);
fplot(handles.grafica,f,[(c-5) (c+5)]);
end
% Hints: contents = cellstr(get(hObject,'String')) returns seleccionar contents as cell array
% contents{get(hObject,'Value')} returns selected item from seleccionar
% --- Executes during object creation, after setting all properties.
function seleccionar_CreateFcn(hObject, eventdata, handles)
% hObject handle to seleccionar (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: popupmenu controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --------------------------------------------------------------------
function Untitled_1_Callback(hObject, eventdata, handles)
% hObject handle to Untitled_1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function ayuda_Callback(hObject, eventdata, handles)
% hObject handle to ayuda (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function acercade_Callback(hObject, eventdata, handles)
% hObject handle to acercade (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
acercade
% --------------------------------------------------------------------
function insttrucciones_Callback(hObject, eventdata, handles)
% hObject handle to insttrucciones (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
instrucciones
% --------------------------------------------------------------------
function borrar_Callback(hObject, eventdata, handles)
% hObject handle to borrar (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.funcion,'string','');
set(handles.xini,'string','');
set(handles.tolerancia,'string','');
set(handles.raiz,'string','');
set(handles.advertir,'string','');
% --------------------------------------------------------------------
function salir_Callback(hObject, eventdata, handles)
% hObject handle to salir (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close
Error:
??? Error using ==> feval
Undefined function or method 'pushbutton1_CreateFcn' for input
arguments of type 'double'.
Error in ==> gui_mainfcn at 96
feval(varargin{:});
Error in ==> untitled at 42
gui_mainfcn(gui_State, varargin{:});
Error in ==>
@(hObject,eventdata)untitled('pushbutton1_CreateFcn',hObject,eventdata,guidata(hObject))
??? Error using ==> struct2handle
Error while evaluating uicontrol CreateFcn
??? Error using ==> function seleccionar_CreateFcn(hObject,
eventdata, handles)
Error: Function definitions are not permitted at the prompt or
in scripts.
??? Error using ==> struct2handle
Error while evaluating uipanel CreateFcn
I need for it to calculate this equation .
sqrt(5*x+2)-x
and automatic calculate the derivative.
endJesséhttps://ch.mathworks.com/matlabcentral/profile/authors/5221019-jessetag:ch.mathworks.com,2005:Question/132312011-08-06T23:15:28Z2019-07-16T22:17:49ZHow do I change the number display from scientific notation to the full number in digits? How to make MATLAB output the full number in digits, and not using scientific notation?Talariahttps://ch.mathworks.com/matlabcentral/profile/authors/2944977-talariatag:ch.mathworks.com,2005:Question/4719572019-07-16T13:52:00Z2019-07-16T22:16:47ZYAxis property of an Axes read-only, but XAxis and ZAxis are not.I discovered that the YAxis property of an Axes is considered read-only, but the XAxis and ZAxis properties can be set and get. I was wondering if there was a specific reason for this, or if this is an oversight. Why is the YAxis property read-only, but the XAxis and ZAxis properties are not?Kathleen Morrisonhttps://ch.mathworks.com/matlabcentral/profile/authors/13620585-kathleen-morrisontag:ch.mathworks.com,2005:Question/4720402019-07-16T22:16:35Z2019-07-16T22:16:35Zhow to calculate the sensitivity and specificityi have create an image splicing detection and i need to caculate its performance using sensitivity and specificity
so how can i apply this formula on the result image for example this image below
Mohammed Kassemhttps://ch.mathworks.com/matlabcentral/profile/authors/14083214-mohammed-kassemtag:ch.mathworks.com,2005:Question/4720362019-07-16T21:54:59Z2019-07-16T22:10:54Z how I can delete 1.0e+03 in my answerclc;clear;
tf=10;
n=1;
dt=0.1;
t(n)=0.1;
G1(n)=1; G2(n)=0; G3(n)=-1; G4(n)=0;
m(n,:)=[1 0 -1 0];
while t(n)<=tf
t(n+1)=t(n)+dt;
m(n+1,:)=m(n,:)+slope(t(n),m(n,:))*dt;
n=n+1;
end
m
this is my code, but when I run it, it gives me like this
m =
1.0e+03 *
0.0010 0 -0.0010 0
0.0010 0.0001 -0.0010 -0.0001
0.0008 0.0002 -0.0009 -0.0002
0.0003 0.0003 -0.0007 -0.0003
-0.0005 0.0003 -0.0004 -0.0004
-0.0013 0.0003 -0.0001 -0.0004
-0.0020 0.0001 0.0002 -0.0004
-0.0026 -0.0001 0.0005 -0.0004
-0.0029 -0.0003 0.0007 -0.0003
-0.0027 -0.0006 0.0007 -0.0003
-0.0021 -0.0009 0.0005 -0.0002
-0.0009 -0.0011 0.0001 -0.0002
my question is how I can delete 1.0e+03 ? should the answer be like this
m =
1.0000 0 -1.0000 0
1.0000 0.1000 -1.0000 -0.1000
0.7500 0.2000 -0.9000 -0.2000
0.2500 0.2750 -0.7000 -0.2900
-0.4525 0.3000 -0.4175 -0.3600
-1.2625 0.2548 -0.0875 -0.4018
-2.0464 0.1285 0.2408 -0.4105
-2.6496 -0.0761 0.5103 -0.3864
Thank youMurad Alzahranihttps://ch.mathworks.com/matlabcentral/profile/authors/10766895-murad-alzahranitag:ch.mathworks.com,2005:Question/2861422016-05-27T21:43:57Z2019-07-16T22:07:56Zrecord audio and get data in real timeHello,
i want to make a recorder in real time, and i get data every 0.01 second with recording parameters(Fs = 8000, nbits = 16 bits, nbChannel = 1), so i want to get the 80 samples (every 0.01) second to analyse them and apply my work.
i used audiorecorder object but no result, when i try to get data it is empty.
Thank youdz despehttps://ch.mathworks.com/matlabcentral/profile/authors/6345621-dz-despetag:ch.mathworks.com,2005:Question/4720352019-07-16T21:45:10Z2019-07-16T22:05:46ZM-script error while run itAfter I made the mathematical equation by the simulink as see in attached photo, then i saved it , I made new script to identify the constants to the simulink then i wrote the sim order with the same name of the simulink project sim('project3test') as u see in attached photo and saved it in the same folder of simulink save file.
when i click run there is an error message in the command window appear as u see in attached photo, while the simulink project is run normally.
What is the probelm for this error and how can i fix it ?
Thanks in advance Ahmed Samirhttps://ch.mathworks.com/matlabcentral/profile/authors/14767407-ahmed-samirtag:ch.mathworks.com,2005:Question/3497392017-07-21T15:03:15Z2019-07-16T22:05:05ZHow to name an excel worksheet when using writetableIs there a simple way to name an the excel worksheet when using the _writetable_ fnx? I am aware of the answer by Thomas Koelen on 8 May 2015 (https://www.mathworks.com/matlabcentral/answers/215703-changing-the-name-of-the-sheet-in-excel) but I am hoping there is a more direct and simple method, not involving ActiveX. Instead of an excel workbook with "Sheet1", "Sheet2", etc I want to give specific names to the worksheets.Stephenhttps://ch.mathworks.com/matlabcentral/profile/authors/4676522-stephentag:ch.mathworks.com,2005:Question/1590572014-10-17T19:06:26Z2019-07-16T22:00:35ZHow can you avoid for loops by using vectorization?I am fairly new to matlab. I am used to coding in C that is why I use a lot for loops but recently I encounter a problem. I am working on assignment for school where I have to run monte carlo simulations for different diversity schemes. I got the simulations to work correctly. However, I am trying to implement this because it takes a very long time to run simulation since I am using a lot for loops. So, I was wondering if someone can help me out with this to avoid for loops and start using vectorization instead, since I know matlab will run faster. below is my code:
stepSize = 1;
M = (1:stepSize:4);
rho = (1:stepSize:18);
S = 1;
disp('Computing...');drawnow;
tic;
for i = 1:length(M)
for j = 1:length(rho)
Sum_MRC = 0;
for k = 0:(M(i)-1)
C = nchoosek((M(i)-1+k),k);
gamma = sqrt(rho(j)/(1+rho(j)));
Sum_MRC = Sum_MRC + (C * ((1+gamma)/2)^k);
end
MRC_Theoretical(i,j) = ((1-gamma)/2)^M(i) * Sum_MRC;
Upper_bound(i,j)= 0.5*(1/(1+rho(j))^M(i));
Error_Counter = 0;
Total_Counter = 0;
while(Error_Counter<100)
hr = randn(1,M(i));
hi = randn(1,M(i));
vr = randn(1,M(i));
vi = randn(1,M(i));
Hm = (hr + (1i*hi));
Vm = (vr + (1i*vi));
Xm = ((sqrt(rho(j))*Hm*S + Vm)/sqrt(2)); %Construction of thefading model channel used.
MRC_Decision = 0;
for k = 1:M(i)
MRC_Decision = MRC_Decision + (Xm(k)*conj(Hm(k)));
%Estimating the decision made by the MRC diversity technique.
end
if (real(MRC_Decision) < 0)
Error_Counter = Error_Counter + 1; %Incrementing theerror counter if the MRC decision is not equal to thee one that is sent.
end
Total_Counter = Total_Counter + 1;
end
Error_Probability(i,j) = Error_Counter/Total_Counter; %Calculating the probability of error based on the Monte Carlo simulations.
end
end
toc;
%Plot for the Monte-Carlo simualtion vs the theoretical values calculated.
figure(1)
semilogy(10*log10(rho),Error_Probability(3,:),'k*:',10*log10(rho),MRC_Theoretical(3,:),'r*:',10*log10(rho),Upper_bound(1,:),'b*:')
xlabel('Signal to Noise ratio');
ylabel('Average probability of error');
legend('Eb for Monte-Carlofor M=3 ','Theoretical Eb','Upperbound','Location','SouthWest');
title('Plot for MRC diversity comparing with Monte Carlo simulation','FontWeight','bold');
%Plot for the all the Theoretical values calculated for all the antennas
figure(2)
semilogy(10*log10(rho),MRC_Theoretical(1,:),'k*:',10*log10(rho),MRC_Theoretical(2,:),'r*:',10*log10(rho),MRC_Theoretical(3,:),'b*:',10*log10(rho),MRC_Theoretical(4,:),'g*:')
xlabel('Signal to Noise ratio');
ylabel('Average probability of error');
legend('Eb for M=1','Eb for M=2','Eb for M=3','Eb for M=4','Location','SouthWest');
title('Plot for MRC diversity for different M values','FontWeight','bold');Angelhttps://ch.mathworks.com/matlabcentral/profile/authors/2284509-angeltag:ch.mathworks.com,2005:Question/4720222019-07-16T20:26:57Z2019-07-16T21:51:25ZUsing Two Model Functions With LSQCUREVFIT My data requires two model functions for the curve fitting. I use one function for the first part of the data, and the second function for the last portion. I have the two model functions in different for loops. The second function picks up in the correct row vector element where the first function leaves off. Both model functions use PredCurrFun as the function name. It appears that the output from the second model function is overwriting the outputs from the first model function. How can I use two model functions in the same LSQCURVEFIT routing? Do I need to call one PredCurrFun and the other PredCurrFun2, and LSQCURVEFIT can use both? I tried setting n = 0 before the first for loop, and then use PredCurrFun(n) hoping that would write the output values in the correct order and position, but I get "Conversion to double from function_handle is not possible". In the code below, that's why there is n = 0 and n = n +1 in the for loops. How do I keep the second function from overwriting the first?
%Initialize Variables
%A = ;
Co = concentration; %Initial concentration in uM, make concentration into row vector i.e. 10 10 10 100 100 100 500 500 500 etc., in same concentration order as current row vector
Diff = 2; %Diffusion coefficient in um^2/ms
T = traceLength; %Trace length row vector
xdata = time;
ydata = current; %Current traces concatenated end to end, beginning with washin traces (lowest concentration to highest), and then washout traces added to end of washin traces (lowest conc. to highest)
%t = time2; %For plotting oberseved data, put time traces in their own column and import as numeric matrix
%y = current2; %For plotting observed data, put current traces in their own column and import as numeric matrix
%Initialize PredCurrFun vector with zeros
PredCurrFun = zeros(1,1271810);
%Plot of actual data
%plot(t1,y,'--b');
%xlabel('Time');
%ylabel('Current');
%Model function used by LSQCURVEFIT - %p(1) is in uM^(-1) ms^(-1), p(2) is
%in ms^(-1), p(3) is in um, total current p(4) is in nA, and p(5) is a
%unitless fraction between 0 and 1.
%Trace Length vector here
[k,m] = size(Co);
%Fitting Wash-in
n = 1;
for i = 1:m
t = 0;
fprintf('t: %d\n', t);
for j = T(i)+1:T(i+1) %Ex. T(1)+1 = 1 to T(1+1) = T(2) = 386610, T(2)+1 = 386611 to T(2+1) = T(3) = 556681, etc...
PredCurrFun = @(p,t) p(5).*p(4) + (1-p(5)).*p(4) .* ((1-p(2)./(p(1).*(Co-(4.*Co)./pi).*exp(-p(1).*(Co-(4.*Co./pi).*exp(-(Diff.*pi^2.*t./(4.*p(2)^2))) + p(2)).*t) ...
+ (p(2) ./ (p(1).*(Co-(4.*Co./pi).*exp(-Diff.*pi^2.*t./(4.*p(3)^2)) + p(2)))))));
t = t + 1;
n = n + 1;
end
end
%Fitting Wash-out
for k = 4:6
t = 0;
fprintf('t: %d\n', t);
for m = T(k)+1:T(k+1) %Ex. T(4)+1 = 945665+1 = 945666 to T(1+4) = T(5) = 973519
PredCurrFun = @(p,t) p(4).*(p(5)+(1-p(5)).*(1-(0.9997).*exp(-p(2).*t)));
t = t + 1;
n = n + 1;
end
end
%Parameter upper, lower, and starting values
lb = [0,0,0,-250,0]; %k1 is in uM^(-1) ms^(-1), k2 is in ms^(-1), L is in um, and total current, I, is in nA
ub = [1E-5,1E-5,300,-50,1];
startingVals = [3E-7,3E-7,10,-140,0.5];
%Non-linear least squares fit of data using model function
format long
options=optimset('disp','iter','LargeScale','off','TolFun',0.000001,'MaxIter',100000,'MaxFunEvals',1000000);
[p,resnorm] = lsqcurvefit(PredCurrFun, startingVals, xdata, ydata, lb, ub, options)
%Chisquare Calculation
ChiSquareRed = resnorm ./ size(ydata)
%Plot LSQCURVEFIT Result
%The number in parentheses next to Co is the row number of the
%concentration column number. For example, Co(1) refers to the first row, which in
%this case was 10 uM, Co(4) refers to the fourth row which was 100 uM, and
%so on.
xgrid = linspace(0,1271810,1271810);
line(xgrid, PredCurrFun(p,xgrid), 'Color', 'r');Kelly McGuirehttps://ch.mathworks.com/matlabcentral/profile/authors/2733866-kelly-mcguiretag:ch.mathworks.com,2005:Question/4720212019-07-16T20:25:53Z2019-07-16T21:51:05ZExtracting file name elements to vectorsHi, I have some climate files separated by minimum and maximum monthly temperatures for a given latitude and longitude from a variety of climate models. I need to combine the two files (tmin and tmax) to create one file with the single average temperature for each month. I'm working on a more elegant, bulk-process solution rather than hard-coded brute force as I have a couple of hundred files to pair up and process. Then I'll be using the average temp files for some analysis.
What I am specifically asking as my question here is how to get elements from the file names into vectors that I can then use to programmatically pair up the tmin and tmax files. I have a very simplified example here:
clear
tmin = [1 1949 -2.54; 2 1949 -0.07];
tmax = [1 1949 16.04; 2 1949 18.74];
% create four files for tmin and tmax for two climate models
fileID = fopen('LatLon_34_-103_tmin_cm1.dat','w');
fprintf(fileID,'%d %d %.2f\n',tmin .');
fclose(fileID);
fileID = fopen('LatLon_34_-103_tmax_cm1.dat','w');
fprintf(fileID,'%d %d %.2f\n',tmax .');
fclose(fileID);
fileID = fopen('LatLon_34_-103_tmin_cm2.dat','w');
fprintf(fileID,'%d %d %.2f\n',tmin .');
fclose(fileID);
fileID = fopen('LatLon_34_-103_tmax_cm2.dat','w');
fprintf(fileID,'%d %d %.2f\n',tmax .');
fclose(fileID);
% build list of files
curDirFiles = dir('*.dat');
fileList = {curDirFiles.name}; %creates a cell array for "contains" function
s = string([34,-103]); % convert lat/lon to string array
search_list = [s,'tmin','tmax']; % build list of strings to search for in file names
file_idx = find(contains(fileList,search_list)); % create index of file names that include the search strings
% extract elements from file names
for i = 1:length(file_idx)
% decompose file name
[latlon,remainder1] = strtok(curDirFiles(file_idx(i)).name,'_');
[lat,remainder2] = strtok(remainder1,'_');
[lon,remainder3] = strtok(remainder2,'_');
[climate_attribute,remainder4] = strtok(remainder3,'_');
[climate_model,remainder5] = strtok(remainder4,'_');
% do stuff
end
As you can see, the for loop at present will only process one file at a time (and only preserve file name elements as scalars good for one loop), which obviously will not allow me to find and access two files at once. Ultimately, I will need to group them by lat, lon and climate model to get the pairs I need to average which is why I'm interested in getting the file elements into vectors.
For example, given the data above, as vectors, I would want to end up with:
lat = [34 34 34 34]
lon = [-103 -103 -103 -103]
climate_attribute = ['tmin' 'tmax' 'tmin' 'tmax']
climate_model = ['cm1' 'cm1' 'cm2' 'cm2']
But in the code above as written, only one file is processed at a time and the file elements are stored as scalars and overwritten with each pass. How do I preserve them into vectors? A bonus would be to do it in a way that eliminates the for loop too, if it's possible.
So I'm wondering if I can do something with arrayfun, for example, that will allow me to process all the files in batch. Arrayfun didn't seem to accept "strtok" as a function, though, since it requires inputs and one "Cannot call or index into a temporary array".
Any ideas how to approach this?Ellen Maashttps://ch.mathworks.com/matlabcentral/profile/authors/8586246-ellen-maastag:ch.mathworks.com,2005:Question/4720242019-07-16T20:33:38Z2019-07-16T21:50:38Zdealing with negative indices errorplease help, i keep getting this error: "Array indices must be positive integers or logical values."
Here is my code:
randn('state',100)
lambda = 2;
mu = 1;
Xnot = 1;
T = 1;
N = 2^8;
r = 0.5;
gamma = 0.5;
delta = 1-gamma;
dt = 1/N;
t = 0.5;
dW = sqrt(dt)*randn(1,N);
W = cumsum(dW);
R = 4;
Dt = R*dt;
L = N/R;
beta = 1.5;
eta = 2;
rho = 0.2;
v = r + (lambda-r)^2/2*delta*mu^2;
D = rho-(gamma*v);
G = delta*(1-exp((D/delta)*(t-T)));
H = (delta*eta)/beta
X_temp = Xnot;
for T = 1
t = -1:1
end
F = X_temp + (((delta*eta)/(beta*r))*(1-exp(r(t-T))));
C = ((D*F)/G)-H;
M = (lambda-r)/(delta*mu^2)
J = (eta*(lambda-r))/(beta*r*mu^2)*X_temp;
pi = M+J
X_EM = zeros(1,L);
for j = 1:L
Winc = sum(dW(R*(j-1)+1:R*j));
X_temp = X_temp + Dt*((pi*(lambda-r)+r)-C) + (mu*pi)*Winc;
X_EM(j) = X_temp;
end
plot([0:Dt:T],[Xnot,X_EM],'g-', 'LineWidth', 2)Gaone Ramadubuhttps://ch.mathworks.com/matlabcentral/profile/authors/15747983-gaone-ramadubutag:ch.mathworks.com,2005:Question/4677952019-06-18T21:31:01Z2019-07-16T21:43:20ZIs there an option for verbose or debug log file when installing MATLAB?Been having issues with installing MATLAB R2019a (and R2018b and R2018a) and I'm wondering if the installer has any option for generating a more detailed log file?Brian Cartyhttps://ch.mathworks.com/matlabcentral/profile/authors/768717-brian-cartytag:ch.mathworks.com,2005:Question/4708292019-07-09T08:00:02Z2019-07-16T21:42:07ZWhy do I get an "Invalid value returned."-error when assigning a string property inside a loop using v18b?When initializing an object of class "Matlab_Dbl_Str_Test" (class in attached file below) in Matlab v18b the result is the following:
When avoiding the try catch block one gets the above mentioned error.
It appears that properties of type string cannot be assigned in a loop whereas properties of type double are perfectly fine.
Is this a known bug or wanted feauture?
%% --------------------------------------------------------------------------
classdef Matlab_Dbl_Str_Test < handle
%UNTITLED2 Summary of this class goes here
% Detailed explanation goes here
properties( Constant )
TEST_STR = ["a";"b";"c"];
TEST_DBL = [0;1;2];
end
properties( SetAccess = protected )
test_str@string as vector;
test_dbl@double as vector;
end
methods
function obj = Matlab_Dbl_Str_Test()
for i = 1:3
try obj.test_str(i) = Matlab_Dbl_Str_Test.TEST_STR(i,1);end
try obj.test_dbl(i) = Matlab_Dbl_Str_Test.TEST_DBL(i,1);end
end
end
function test( obj )
for i = 1:3
try obj.test_str(i) = Matlab_Dbl_Str_Test.TEST_STR(i,1);end
try obj.test_dbl(i) = Matlab_Dbl_Str_Test.TEST_DBL(i,1);end
end
end
end
endDaniel Stützlehttps://ch.mathworks.com/matlabcentral/profile/authors/11192857-daniel-stutzletag:ch.mathworks.com,2005:Question/4720332019-07-16T21:40:43Z2019-07-16T21:40:43ZConfigurate PID in simulinkHi.. my answer may not be clear because I am not familiar to work on simulink.
I want to associate 4 PI in one block but I need to configure two of them to appear as 'zeros' as in the picture belew.
thanks for reviewing my questionzakaria debihhttps://ch.mathworks.com/matlabcentral/profile/authors/10133723-zakaria-debihtag:ch.mathworks.com,2005:Question/4720312019-07-16T21:29:30Z2019-07-16T21:38:41ZExponential terms in numerator and denominator in a Transfer FunctionI have the LTI system in the attachement and written below. Though, I am having difficulties typing it into Matlab. Is this possible with the exponentials?
num=exp(sqrt(s/alpha)*H)+exp(sqrt(s/alpha)*H)
den=A*R*(k*sqrt(s/alpha)+h_surface)*(exp(sqrt(s/alpha)*H)-exp(-sqrt(s/alpha)*H)
Please see the attachement for a clearer figure.
Thank you
Jacob Johnhttps://ch.mathworks.com/matlabcentral/profile/authors/7044775-jacob-johntag:ch.mathworks.com,2005:Question/4530772019-03-28T14:54:17Z2019-07-16T21:37:30ZLogitech G29 with simulinkHi
I have a logitech G29 driving wheel and pedals on PS3 mode and the simulink realtime library block for Logitech G29. Do you have any idea how can I record steering signals?
I keep on getting error though all the modules and drivers are installed in Matlab.HUSAIN KANCHWALAhttps://ch.mathworks.com/matlabcentral/profile/authors/12061588-husain-kanchwalatag:ch.mathworks.com,2005:Question/1570292014-10-02T00:44:13Z2019-07-16T21:34:29Zgetting coordinates from a picture<</matlabcentral/answers/uploaded_files/18843/Part1.JPG>>
Hi!
I have an image that I would like to get the coordinates from. Its a 2D image. I need to perform some operation with the image.
I need to get the coordinates of some points I choose and get them saved.
I am aware of the data cursor, but since I have a huge number of points, manual operation will be of no way.
lets say, I have this basic structure of a thermal fin. I need say 1000 points from its boundary.Is there any way in matlab, I can import the image, and save the coordinates of the boundary, distributed evenly over.
I hope my question is clear.
thanks in advance!!
aadityahttps://ch.mathworks.com/matlabcentral/profile/authors/3941062-aadityatag:ch.mathworks.com,2005:Question/4720302019-07-16T21:29:07Z2019-07-16T21:32:03Zhow to convert an ecg signal to image 2Dhello everyone
can someone help me to generate an image 2D from an ecg signal :
the main idea is to determine the RR intervalle in seconde ,the image that will be find contain the number of samples in raw and the times in column,
here is a pdf file explain the futur image.
please im really need your help
clc;
close all;
close all;
load 'ECG_3.mat'
N=length(ECG_3);
fs=2155;
t=[0:N-1]/fs; subplot (221);
plot(ECG_3) ;grid on
title('Original Signal')
xlabel('samples');ylabel('Amplitude(v)');
%%
%Low pass filter
b=1/32*[1 0 0 0 0 0 -2 0 0 0 0 0 1];
a=[1 -2 1];
sigL=filter(b,a,ECG_3);subplot(222);
plot(sigL);grid on
title('Low Pass Filter')
%%
% BASE LINE DERIVATION
b=[1/4 1/8 0 -1/8 -1/4];
a=[1];
sigD=filter(b,a,sigL);subplot(223)
plot(sigD);grid on
title('Derivative Base Filter')
%% Measuring Distance Between Peaks
%Find R peaks
[pks_Rwave,locs_Rwave] = findpeaks(sigD,'MinPeakHeight',0.5,'MinPeakDistance',200);
fprintf('locs_Rwave = \n');
disp (locs_Rwave)
pks_Rwave1 = pks_Rwave*100;
fprintf('pks_Rwave = \n');
disp (pks_Rwave1);subplot (224);
plot(time,sigD,time(locs_Rwave),pks_Rwave,'rv','MarkerFaceColor','r'); grid on
xlabel('Time'); ylabel('Voltage');
title('Find Prominent Peaks');
%% RR INTERVAL
i = 0; %% to make the code start from 0.
rr = 0; %% each time the code run, rr distance two peaks
hold off % for the next graph
rrinterval = zeros(3600,1); % create an array to strore 2 peaks
beat_count =0;
for k = 2 : length(sigD)-1
%the peak has to be greater than 1 and greater than the value before it and greater then the value after it.
if(sigD(k)> sigD(k-1) && sigD(k) > sigD(k+1) && sigD(k)> 1);
beat_count = beat_count +1;
if beat_count ==1;
rr =0;
else
rr = k-i;
rrinterval(k)=rr;
i=k;
end
else
rrinterval(k)= rr;
end
end
figure;
plot (rrinterval);
title('R-R intervals');karima neffatihttps://ch.mathworks.com/matlabcentral/profile/authors/13249018-karima-neffatitag:ch.mathworks.com,2005:Question/4720292019-07-16T21:17:27Z2019-07-16T21:23:38ZIndex exceeds the number of array elements (1).clc;clear;
tf=10;
n=1;
t(n)=0.1;
dt=0.1;
G1(n)=1; G2(n)=0; G3(n)=-1; G4(n)=0;
m(n,:)=[1 0 -1 0];
while t(n)<=tf
m(n+1,:)=m(n,:)+slope(t(n),m(n,:))*dt;
n=n+1;
end
It shows me like Index exceeds the number of array elements (1)
Error in cars (line 8)
while t(n)<=tf
and this is my fucntion.
function [out] = slope(t,G)
k1=10;k2=20;m1=2;m2=4;
v1=G(1); x1=G(2);v2=G(3);x2=G(4);
out(1)=(-k1*x1+k2*(x2-x1))/m1;
out(2)=v1;
out(3)=-k2*(x2-x1)/m2;
out(4)=v2;
end
why? how I can fix it?
Thank youMurad Alzahranihttps://ch.mathworks.com/matlabcentral/profile/authors/10766895-murad-alzahranitag:ch.mathworks.com,2005:Question/28972011-03-10T08:38:08Z2019-07-16T21:21:29ZReed Solomon encoding This is the RS encoding I found online:
RSdata = reshape(x,8,length(x)/8);
RSdata = bi2de(RSdata.','left-msb');
RSdata = [RSdata.' 0];
msg = gf(RSdata,m);
codeRS = rsenc(msg,n,k);
out = codeRS.x ;
RSdata_out=double(out);
RSdata_out=[RSdata_out(end-d+1:end) RSdata_out(1:end-d)];
RSdata_out=de2bi(RSdata_out,'left-msb');
RSdata_out=reshape(RSdata_out.',length(RSdata_out)*8,1);
The x represents the random data generated. I need this RS encoding in the simulation of wimax physical layer. As defined in IEEE, for a 16-QAM modulation, the [n,k] RS encoding has a value of n = 64 and k = 48. I try this code and it works well only if the input bits is of a matrix [47*8 1]. I change the input bits and this is the error message I got :
Error using ==> rsenc at 82
MSG must be either a K-element row vector or a matrix with K columns.
Error in ==> RS16QAM at 25
codeRS = rsenc(msg,n,k);
I can't figure out what's the relation between the input size and the rs encoding thing. Anyone encounter the same error message before or has any idea about this? Thank you very much in advance! =)Linghttps://ch.mathworks.com/matlabcentral/profile/authors/2772650-lingtag:ch.mathworks.com,2005:Question/4111392018-07-19T13:21:16Z2019-07-16T21:18:59ZWhy Basler acA does not show in Image Acquisition ToolI am running Debian 9.5
In matlab I have installed the gentl drivers and I have installed the pylon viewer.
In pylon viwer I can preview the cameras, but they do not show in the Image Acquisition Tool
I have done this before on Wondows 10 and then all I had to do (in Matlab) was to install the gentl packadge.
See attached imaqsupport.txt
If I try to connect to the cameras through
videoinput('gentl',1,'Mono8')
I get:
Error using videoinput (line 235)
There are no devices installed for the specified ADAPTORNAME. See IMAQHWINFO.
Please help me.uwVisionhttps://ch.mathworks.com/matlabcentral/profile/authors/9624108-uwvisiontag:ch.mathworks.com,2005:Question/4720192019-07-16T20:11:55Z2019-07-16T21:12:25ZError using function. I get the error Array indices must be positive integers or logical values.clear all
clc
format short
lambda = 0.9;
ES = zeros(5);
SCV = ES; %initializing SCV
TH = ES; %initializing TH
EW = ES; %initializing EW
% a = 1:5;
% b = a;
% nodes = create_nodes(a, b);
for i=1:5
for j=1:5
ES(i,j) = 5-abs(i-3)-abs(j-3); %compute service time
SCV(i,j) = abs((i-3)*(j-3)); %compute scv
end
end
EW(1,1) = ES(1,1)*(1+0.5*(1+SCV(1,1))*0.9*1*ES(1,1)/(1-0.9*1*ES(1,1)));
V(1,1) = 1;
V(1,2) = 0.5;
EW(1,2) = ES(1,2)*(1+0.5*(1+SCV(1,2))*0.9*V(1,2)*ES(1,2)/(1-0.9*V(1,2)*ES(1,2)));
x(4) = 0.5;
x(7) = 0.5;
x(9) = 0.5;
V_init = 0.5;
for i = 3:5 % compute sojourn time for row 1
V_fun{i} = @(x) V_init*x(i-2);
EW_fun{i} = @(x) ES(1,i)*(1+0.5*(1+SCV(1,i))*0.9*V_fun{i}*ES(1,i)/(1-0.9*V_fun{i}*ES(1,i)));
V_init = @(x) V_fun{i};
fun{i} = @(x) V_fun{i}*EW_fun{i};
end
V_init = 1;
for j = 6:8 % compute sojourn time for row 2
V_fun{j} = @(x) 0.5*(1-x(1))*V_init*x(j-2);
EW_fun{j} = @(x) ES(2,j-3)*(1+0.5*(1+SCV(2,j-3))*0.9*V_fun{j}*ES(2,j-3)/(1-0.9*V_fun{j}*ES(2,j-3)));
V_init = @(x) V_fun(j);
% fun{j} = @(x) V_fun(j)*EW_fun{j};
end
V_init = 0.5*x(1)*(1-x(2))*(1-x(5));
for i = 9:10 % compute sojourn time for row 3
V_fun{i} = @(x) V_init*x(i-2);
EW_fun{i} = @(x) ES(3,i-5)*(1+0.5*(1+SCV(1,i-5))*0.9*V_fun{i}*ES(1,i-5)/(1-0.9*V_fun{i}*ES(1,i-5)));
V_init = @(x) V_fun{i};
% fun{i} = @(x) V_fun{i}*EW_fun{i};
end
V_fun{11} = @(x) 0.5*x(1)*x(2)*(1-x(3))*(1-x(6))*(1-x(8))*x(9);
EW_fun{11} = @(x) ES(4,5)*(1+0.5*(1+SCV(4,5))*0.9*V_fun{11}*ES(4,5)/(1-0.9*V_fun{11}*ES(4,5)));
% fun{11} = @(x) V_fun{11}*EW_fun{11};
V_fun{12} = @(x) 0.5*x(1)*x(2)*x(3)*x(10);
EW_fun{12} = @(x) ES(5,5)*(1+0.5*(1+SCV(5,5))*0.9*V_fun{12}*ES(5,5)/(1-0.9*V_fun{12}*ES(5,5)));
% fun{12} = @(x) V_fun{12}*EW_fun{12};
% funMin = @(x) sum([fun{:}])
V_fun{1} = V(1,1);
V_fun{2} = V(1,2);
EW_fun{1} = EW(1,1);
EW_fun{2} = EW(1,2);
% fun{1} = @(x) V_fun{1}*EW_fun{1};
% fun{2} = @(x) V_fun{2}*EW_fun{2}
fun = @(x) cellfun(@(g,h)(g(x)*(h(x))),V_fun,EW_fun);
funMin = @(x) sum([fun{:}]);
x0 = zeros(1,10);
Aeq = [];
beq = [];
lb = zeros(1,10);
ub = ones(1,10);
x = fmincon(fun,x0,[],[],Aeq,beq,lb,ub);Niveditha Kumarhttps://ch.mathworks.com/matlabcentral/profile/authors/12182643-niveditha-kumartag:ch.mathworks.com,2005:Question/4720272019-07-16T21:10:25Z2019-07-16T21:10:25ZHow can I find the point of tangential intersection between an ellipsoid of changing size and a plane?I have a function for an ellipsoid that I need to change slightly iteratively until the ellipsoid intersects a defined plane tangentially and I need the output of several variables at that point. I'll show some code and try to explain further with comments.
%Variables
t0 = .5;
h = 0;
f = 90;
w = 0;
v = 1900;
dipindegrees = 0;
azimuthindegrees = 0;
theta = atan(w/h);
dip = (90-dipindegrees)*pi/180; %DO NOT CHANGE - Converts dip to rads
azimuth = azimuthindegrees*pi/180; %DO NOT CHANGE - Converts azimuth to rads
zp = v*t0/2; %Depth to reflector at MP
point = [0,0,-zp]; %Midpoint of source-receiver
a = cos(dip)*sin(azimuth)/sqrt(cos(dip)*sin(azimuth)+cos(dip)*cos(azimuth)+sin(dip));
b = cos(dip)*cos(azimuth)/sqrt(cos(dip)*sin(azimuth)+cos(dip)*cos(azimuth)+sin(dip));
c = sin(dip)/sqrt(cos(dip)*sin(azimuth)+cos(dip)*cos(azimuth)+sin(dip));
d = -(a*point(1)+b*point(2)+c*point(3));
[p1,p2] = meshgrid(-5000:2:5000);
p3 = (a*p1 - b*p2 - d)/c;
%[p1 p2 p3] is the plane
k1 = 0; k2 = 0; k3 = 0;
tFinal = 0;
flag = 0;
if h == 0
theta = 0;
end
for t = .5:.1:5 %Changing t changes the size of the ellipse
tx = sqrt(t^2+(2*h)^2)/(v^2);
l =v*(tx)/2;
[e1,e2,e3] = ellipsoid(0,0,0,sqrt(l^2-h^2),l,sqrt(l^2-h^2),5000); %make ellipsoid
%At this point I try to compare the coordinates of the ellipse and plane to find where they are equal and save these coordinates as [k1 k2 k3]...
%and return the t value at which this occurs.
for val1 = 1:5001
for val2 = 1:5001
for val3 = 1:5001
for val4 = 1:5001
if e1(val1,val2) == p1(val3,val4) && e2(val1,val2) == p2(val3,val4) && e3(val1,val2) == p3(val3,val4)
k1 = e1;
k2 = e2;
k3 = e3;
tFinal = t;
flag = 1;
break
end
if flag == 1
break
end
end
if flag == 1
break
end
end
if flag == 1
break
end
end
if flag == 1
break
end
end
if flag == 1
break
end
endNick McDanielhttps://ch.mathworks.com/matlabcentral/profile/authors/15365755-nick-mcdanieltag:ch.mathworks.com,2005:Question/4719292019-07-16T11:52:37Z2019-07-16T21:10:15ZRemoving data from a structure that is less than a certain thresholdI am running a code to find the positions and trajectories of microparticles. I get a lot of noise as my particle concentration is quite dense. The false positives slow down my code significantly so I want to get rid of them every loop so I have made the following code:
c=1;
while c <= length(AllTraj.Passive)
if ((length(AllTraj.Passive(c).T) <= 10) && ...
(max(AllTraj.Passive(c).T) < (i-2)))
AllTraj.Passive(c) = [];
else
c=c+1;
end
c
end
AllTraj.Passive represents a struct with my connected particle trajectories each with time (T), X and Y values.
I want to get rid of any particles (rows) which have a trajectory of length 10 or less if they are no longer being tracked in the current frame (i-2 is current frame).
This code seems to run very slowly when I have a lot of particles and when I clear the rows which meet the criteria.
Is there a faster way to remove data that is less than a threshold time?
Thanks Manny Kinshttps://ch.mathworks.com/matlabcentral/profile/authors/9135788-manny-kinstag:ch.mathworks.com,2005:Question/4720062019-07-16T18:54:23Z2019-07-16T21:07:00ZCalculate the distance between matched pointsHello,
I have two sets of matched points (matchedPoints1 and matchedPoints2, the size is 142x1 and the type is SURFPoints) and I want to calculate the distance between them. I tried the function pdist2() like this :
dist_matchedPoints=pdist2(matchedPoints1,matchedPoints2,'euclidean');
But I got the following error :
Error using cast
Unsupported data type for conversion: 'double'.
Error in pdist2 (line 250)
X = cast(X,outClass);
I don't really understand the meaning of this error message so can somebody help me to solve this problem ?
Thanks a lot.
Théodore Kellerhttps://ch.mathworks.com/matlabcentral/profile/authors/14853595-theodore-kellertag:ch.mathworks.com,2005:Question/4720262019-07-16T21:00:18Z2019-07-16T21:00:18ZHow weights are used in RLowess algorithmI have a question regarding RLowess. On this page under Robust Local Regression. In the third step, it says "Smooth the data again using the robust weights. The final smoothed value is calculated using both the local regression weight and the robust weight". I am a little bit confused here, does this mean after computing robust weights, first the algorithm calculates Y values using the robust weights, then again caluclates Y values using both the local regression weight and robust weight? Or just after computing robust weights, it uses both of the weights (the local regression weight and robust weight) to calculate Y values? Furthermore, how the two weights are combined together? Does it mean each Wi is the multiplication of its corresponding local regression weight and robust weight? Nick Zadehhttps://ch.mathworks.com/matlabcentral/profile/authors/6804458-nick-zadehtag:ch.mathworks.com,2005:Question/4718062019-07-15T17:49:49Z2019-07-16T21:00:14Zplot a surcafe having different length vectors and cell arrayHello,
I have a cell array of 7x7(see the picture). Inside every cell there are different number of values. For example in (2,2) there are 4 values and in (2,7) are 5.
I want to create a scatter or a surface plot in which:
In X axis be a row vector 1x7 (mppvals,see the picture)
In Y axis be a row vector 1x7 (uvals,see the picture)
And in the Z axis be every number of the cell array in every condition.
For example when the X has the second value of the row vector (1.60 an Y has also the second value of the other row vector (0.1), in the Z axis will be the values of (2,2) from the array.
Ilias Minashttps://ch.mathworks.com/matlabcentral/profile/authors/13907044-ilias-minastag:ch.mathworks.com,2005:Question/4720252019-07-16T20:59:48Z2019-07-16T20:59:48ZOutputting function into multiple columns of matrixI have a existing matrix M: r x 14 x d double
I have a function that takes in matrix: r x 6 x d double and it apparently outputs the same shape back.
The function manually names each column to a variable (say a1 - a6) , then outputs them in format [A1, A2, ..., A6]
I give it: M(:,[1:4 8:9],:), which is r x 6 x d, and I get back from function ans = r x 6 x d
However, when I am trying to re-insert the ans back into the same columns they came from (M(:,[1:4 8:9],:)), I get an error:
"Subscripted assignment dimension mismatch."
This is what I am trying:
M(:,[1:4 8:9],:) % outputs shape r x 6 x d double
M(:,[1:4 8:9],:) = MyFun(M(:,[1:4 8:9],:) )
function [A1, A2, A3, A4, A5, A6]= MyFun(vals,:) )
A1 = vals(:,1,:);
A2 = vals(:,2,:);
% And so on... Shape of each is 584 x 1 x 4
[A1, A2, A3, A4, A5, A6] % outputs shape r x 6 x d double
end
Is there a way to do this in one line similar to the above? Or is it just silly mistake etc.
Many thanks for any helpmichael hosseinihttps://ch.mathworks.com/matlabcentral/profile/authors/13091065-michael-hosseinitag:ch.mathworks.com,2005:Question/4719762019-07-16T15:24:15Z2019-07-16T20:49:41ZHow to perform the absolute value function on the output of an optimisation expression?% Create Optimisation expressions
j = length(x); % is a double array
Tk = optimexpr(j);
Uk = optimexpr(j);
energyCost = optimexpr(j);
thermalCost = optimexpr(j);
%Initialise optimisation expressions
Tk(1,1) = 22;
Uk(1,1) = Tk(1,1)*K; % K=0.6
energyCost(1,1) = Uk(1,1)*abs(x(1,1));
thermalCost(1,1) = abs(Tk(1,1)-nominal_T); % THIS WHERE THE PROBLEM IS
% The last line always produces an error... "Undefined function 'abs' for input arguments of type 'optim.problemdef.OptimizationExpression'"
% How can I get round this?Akinkunmi Adegbenrohttps://ch.mathworks.com/matlabcentral/profile/authors/6270247-akinkunmi-adegbenro