https://www.mathworks.com/matlabcentral/answers/questionsMATLAB Answers — New Questions2019-10-14T00:42:05Ztag:www.mathworks.com,2005:Question/4851082019-10-14T00:39:04Z2019-10-14T00:42:05ZRoot finding using a loop structureFor simplicity, let's say there is an equation
y= 8x + 97
If I want to find x that makes y = 0, how should I use an looping structure (ex. for, while, if)?Jaeweon Leehttps://www.mathworks.com/matlabcentral/profile/authors/10911921-jaeweon-leetag:www.mathworks.com,2005:Question/4851092019-10-14T00:39:45Z2019-10-14T00:39:45ZHow to obtain output voltage ripple waveform and inductor current ripple waveform for Buck Boost converter on Simulink?Using the circuit from the command "power_BuckBoostConverter" , how can I obtain output voltage ripple waveform and inductor current ripple waveform?Miguel Hernandezhttps://www.mathworks.com/matlabcentral/profile/authors/5109312-miguel-hernandeztag:www.mathworks.com,2005:Question/4848932019-10-12T08:44:18Z2019-10-14T00:37:22Z how to solve this error "Subscripted assignment dimension mismatch."I tried looping through 231 samples of data but the error below occurs,
Subscripted assignment dimension mismatch.
Error in tvf_emd (line 132)
imf(nimf,:)=y(ind_remov_pad);
if flag_stopiter
for row_number = 1 : size(imf,1);
end
imf(nimf,:)=y(ind_remov_pad);
temp_x=temp_x - y(ind_remov_pad);
break;
each Imf is supposed to be 50x 500 but due to the 231 data samples , the imf matrix multiplies to become 50 x 115500.
This causes the above error even though I tried looping through each sample.
Please I will be grateful for any help.
Yussif Moro Awelisahhttps://www.mathworks.com/matlabcentral/profile/authors/13640172-yussif-moro-awelisahtag:www.mathworks.com,2005:Question/4851052019-10-14T00:26:27Z2019-10-14T00:37:09ZMoving 3D patch object along a trajectoryHello
I created a 3D object with the patch function. I want to move this object along a trajectory, where the coordinates are functions of time. I want to move the object along the trajectory and show the plot as an animation of the object's motion by generating the path coordinates with a for loop, with time being the variable that changes with each iteration. I want to move the object by adding the coordinates of its original vertices to those of the path, dependent on time. I am not sure how to do this though. Any help would be appreciated. Thank you.Grant Colehttps://www.mathworks.com/matlabcentral/profile/authors/11941465-grant-coletag:www.mathworks.com,2005:Question/4849472019-10-12T18:16:34Z2019-10-14T00:34:39Z how do i use the rand command in an array of an image, i want the program to read the image and draw some elements from that array
how do i use the rand command in an array of an image, i want the program to read the image and draw some elements from that arrayFelipe Kogahttps://www.mathworks.com/matlabcentral/profile/authors/12867056-felipe-kogatag:www.mathworks.com,2005:Question/4826632019-09-29T01:46:49Z2019-10-14T00:34:33ZHow to change the Matlab panel color?I found the color setting for editor and command line in the preference. But as for the background of panel of tools(file, variable, code...) or the name of directory? Is it possible to change it to black and set the font to be white?wei zhanghttps://www.mathworks.com/matlabcentral/profile/authors/3994770-wei-zhangtag:www.mathworks.com,2005:Question/4851042019-10-14T00:08:04Z2019-10-14T00:30:36ZArgument of a function includes another functionHi all,
I have a file called "fofx.m", and it has this function
function y = fofx(x)
y = cos(x) - sin(x);
end
In another file (same directory), I have
function [l,r,nf] = bisect(fname,a,b,tol)
if(a == b)
if(fname(a) == 0)
l = a;
r = l;
nf = 0;
return;
end
end
The evaluation of fname at a is giving me trouble. I get a different error message, no matter how I try get this function evaluated. How can I evaluate fname at a?Nicole Striplinghttps://www.mathworks.com/matlabcentral/profile/authors/9998377-nicole-striplingtag:www.mathworks.com,2005:Question/4851072019-10-14T00:30:30Z2019-10-14T00:30:30ZWhile Loop, question how to implement itHi everybody, I was wondering how to change a while loop with an “if” condition to an a simple while. For example I got
n=100;
x=rand(1,n);
k=1;
while k<n
if x(k) > 0.95
break;
end
k=k+1;
end
disp([num2str(k), ‘ is the index of the first element in x that is greater than 0.95’]);
ThanksRaul Garciahttps://www.mathworks.com/matlabcentral/profile/authors/14544316-raul-garciatag:www.mathworks.com,2005:Question/4851062019-10-14T00:29:51Z2019-10-14T00:29:51Zkalmd gain L in descriteI'm using kalmd() function to get Kalman gain L, but it gives me error for my Rn(Measurement noise) value as below.
and this is the error.
Can anyone tell how can I fix this error?
I have tried with Ro manually by making Ro is not singular, for example Ro = [0.1,0.01;8,0.1];
it it calculates kalman gain L, however, command gives warning as below.
I am not sure is it because I am handling with kalmand descrite gain.
Please help, Thanks adavance.WANYI ZHANGhttps://www.mathworks.com/matlabcentral/profile/authors/10666035-wanyi-zhangtag:www.mathworks.com,2005:Question/4851012019-10-13T23:34:21Z2019-10-14T00:28:11ZRename and save multiple .mat files.Hi
I am trying to load, rename and save a group of mat files . so far I am using this code :
cd 'E:\Mat'
fileFolder = fullfile('E:\','Mat');
% cd (fileFolder)
dirOutput = dir(fullfile(fileFolder,'*.mat'));
fileNames = {dirOutput.name};
for k=1:length(fileNames)
H=fileNames{k};
movefile(H, sprintf('All_state_action_qs_%03d.mat', k));
end
although it does rename all the files properly, when I load any files (with new name) the name on the work space is the old name.
Therfore, I guess there is a way for doing Load>Rename>save again in a batch fashion.
regards
caesarhttps://www.mathworks.com/matlabcentral/profile/authors/7647654-caesartag:www.mathworks.com,2005:Question/4850392019-10-13T14:28:10Z2019-10-14T00:21:35ZPlotting data as a function of timeI'm just trying to understand plotting prices as a function of time, if I have price data of prices in a column, say x=[1;2;3;4;5;6;7;8;9;13;14;15] and creating a time axis of integers from 1 to the number of days so 1:length of the first colum am I correcting in the definition of plotting the prices as a function of time by.
numberofdays=size(x,1)
plot(1:numberdays,x(:,1)) %equivalent to plot(t,y) where x(:,1) are the first column price values
jacob Mitchhttps://www.mathworks.com/matlabcentral/profile/authors/16429293-jacob-mitchtag:www.mathworks.com,2005:Question/4848602019-10-11T22:47:11Z2019-10-14T00:19:25ZHow to extract text from string at the same location, one line aboveI have a variable number of text files (between 3-8), each between 20,000 and 30,000 lines long (different lengths), and around 400 words to search for. The words have different lengths.
Let's say I have the following text:
xxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxx999xxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxx12345xxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
where xxxxx can be anything other than what I want to search for. I want to make check whether the following is true:
That each text file includes '12345'
That for at least one occurrence of '12345' in each file, there is '999'. The end of '999' always coincides with the end of '12345'.
I can determine whether '12345' is in each of the text files using strfind, but strfind only ouputs an "index" value for the first character of my search pattern (e.g. 613587). Is there a way to find the line number that "index" value corresponds with, and search one line above for '999'?
I think I saw people recommending that each line for each file be read as a separate string, then search each string independently, but that seems like a lot of work for MATLAB to go through, having to generate close to a hundred thousand strings. Is there a better/more efficient way of achieving this?
Any help would be appreciated!zherthttps://www.mathworks.com/matlabcentral/profile/authors/15462388-zherttag:www.mathworks.com,2005:Question/4850122019-10-13T11:15:14Z2019-10-14T00:13:59ZSaving the values into a txt file and then uploading it to edit text boxes buttonsHy Guys. I need your help as I am working on a project. I have created my own GUI. I need to save the values from the edit text boxes of the GUI into the Parameters.txt file, which I created in the Notepad. This will happen when I click on the save button. If I type a value in the edit text box string, it must be saved in the text file. After that I will upload the values to the edit text boxes, when I click on the upload button from the Parameters.txt file. The problem with my code is that it asks for file selection and then opens the file when I click on it. But, it does not save the value to the file. Also, my Parameters.txt file is empty right now. My code for pushbutton save is shown below:
function pushbutton_Save_Callback(hObject, eventdata, handles)
[FileName,PathName]= uigetfile('*.txt','browse')
%[handles.FileName,handles.PathName] = uigetfile({'Parameters.txt'}, '.txt');
file=fullfile(FileName,PathName)
fid = fopen(file,'wb');
b = get(hObject,'String');
fprintf(fid, '%s\n', b{:});
fclose(fid);
I am getting errors with all fprintf and fscanf command even though I have tried with several ways.
My errors are:
Error in GUI_ParametersFinal>pushbutton_Save_Callback (line 125)
fprintf(fid, '%s\n', b{:});
Error in gui_mainfcn (line 95)
feval(varargin{:});
Error in GUI_ParametersFinal (line 42)
gui_mainfcn(gui_State, varargin{:});
Error in @(hObject,eventdata)GUI_ParametersFinal('pushbutton_Save_Callback',hObject,eventdata,guidata(hObject))
Can you help me fix this saving of the values into the file issue? It will be great and so nice of you. I tried with the way shown in the link below as well, but its not working for me:
https://uk.mathworks.com/matlabcentral/answers/10856-save-value-from-edit-text-box-from-gui-in-a-text-file-and-on-start-load-value
Help will be greatly appreciated. Thank you so much :)MHShttps://www.mathworks.com/matlabcentral/profile/authors/12763488-mhstag:www.mathworks.com,2005:Question/4850852019-10-13T21:03:31Z2019-10-14T00:10:26ZConvert a tetrahedron mesh to triangular mesh or surface mesh.Hi,
I have a stl file and generated the 3d mesh using generatemesh from PDE toolbox. But the output is tetrahedron mesh, I need only the surface mesh for that stl. I need to do with pdetoolbox only, because generatemesh is giving finer details of the 3d object. Basic code which I have tried is below. msh has faces of (n,4). So I need a surface mesh from this, I need a output of (n,3) which row indicate a connection of 3 vertices on surface. Any help is much appreciated.
model = createpde(3);
importGeometry(model,'example.stl');
msh = generaeMesh(model,'GeometricOrder','linear');Naga Durga Harish Kanamarlapudihttps://www.mathworks.com/matlabcentral/profile/authors/11738994-naga-durga-harish-kanamarlapuditag:www.mathworks.com,2005:Question/4851032019-10-13T23:52:59Z2019-10-13T23:52:59ZMaking a GUI for steganography, function is already complete just want to pointI wrote a function to encode and decode text to/from an image. The encoder takes in 4 variables.
function Encoder(msg,key,inputimg,outputname)
How do I write the code for the app designer if all I want to do is send those four variables? The output is to save an image. When I run it in matlab editor it works as a function, but how would I apply this in the editor? I have looked at several sources but some of it is for the old "Guide" version and I am not sure if it is written the same way in the App Designer. Here is what I wrote for the callback for the button that should trigger the function. I put in the comments of some things I saw but never fully understood (comments dont refer to the actual code).
% Button pushed function: EncryptButton
function EncryptButtonPushed(app, event)
msg=app.Message2HideTextArea.Value % handles=guidata(hObject);
key=app.KeyEditField.Value % msg=get(handles.Message2HideTextArea, 'string');
inputimg=app.InputImageEditField.Value % set(handles, CALL FUNCTION Encoder?, 'string', msg);
outputname=app.OutputNameEditField.Value % guidata(hObject, handles);
Encoder(msg,key,inputimg,outputname)
end
The way I would like it to work
First box: the input text you want to send, ideally without the single commas (') around it like in MATLAB.
2nd box: the key, a combination in binary of 7 bits (e.g. 0 0 0 1 0 0 0, ideally without the brackets ([) around it like in MATLAB. Must be 7.
3rd box: the file finder, it browses for the image, or is an image name in an assumed folder.
4th box: similar to the 3rd box but for the encoded image name.
Thank you to anyone who can help or refer me.Thomas Fodorhttps://www.mathworks.com/matlabcentral/profile/authors/16390242-thomas-fodortag:www.mathworks.com,2005:Question/2785602016-04-12T08:31:07Z2019-10-13T23:40:34ZDividing speech signal into short-time segments?Hi all. I created a speech signal in Matlab. I need to divide speech signal into short-time segments with lengths 150 samples.
Later I will process each segment to determine if it is voiced or unvoiced, and pitch period for voiced speechs.
Here is the info:
<</matlabcentral/answers/uploaded_files/49667/info.jpg>>
jack starhttps://www.mathworks.com/matlabcentral/profile/authors/7956810-jack-startag:www.mathworks.com,2005:Question/4849452019-10-12T17:52:49Z2019-10-13T23:39:37ZPlotting Sum of seriesHi all,
I want to plot the tempersature distribution:
For x = 0.5 (constant) and y =0:0.1:2;
I used the code below which give me an error:
Error using plot
Data must be numeric, datetime, duration or an array convertible to double.
What am I doing wrong?
Thnx
Jan
clear
clc
x = 0.5;
h = 0.1;
ymax = 2;
y = 0:h:ymax;
syms n
T = 273+symsum(400/sinh(2*pi*n)*n*pi*(1-((-1)^n)*cos(1))/((1-(n^2)*(pi^2))^2)*sin(n*pi*x)*sinh(n*pi*y), n, 1, Inf);
plot(T,y);
xlegend("Static Temperature (c)");
ylegend("Position (m)");jan van doornhttps://www.mathworks.com/matlabcentral/profile/authors/8768807-jan-van-doorntag:www.mathworks.com,2005:Question/4851022019-10-13T23:38:14Z2019-10-13T23:38:14ZProcessing WAV file using SMA filter, and plot the frequency response and impulse response for the single and the filter How i can process wav file using an SMA filter ? how i desing the filter! and how i plot the impulse response, frequency response, and pole-zero plot for the filter ?
how i use
[h,t] = impz(b,a)
and
[h,w]=freqz(b,a,n)
what shoud be my a,b,and n ? i can read y and fs only !
here is what i have !
[y,Fs] = audioread('file.wav');
Info= audioinfo('file.wav') ;
N = length(y);
t = linspace(0, N/Fs, N);
dF = Fs/N;
f = -Fs/2:dF:Fs/2-dF;
X = fftshift(fft(y));
plot(f,abs(X)/N);
plot(t, y);Anonymous Userhttps://www.mathworks.com/matlabcentral/profile/authors/8715977-anonymous-usertag:www.mathworks.com,2005:Question/4850982019-10-13T22:44:52Z2019-10-13T23:36:30Zreading tiff image in matlabHow to read correct pixel values from the Tiff image in matlab? Can somebody send me the syntax for that? I want to read 1024 X 1024 X 30 tif image .Ashwinraj Gnanavelhttps://www.mathworks.com/matlabcentral/profile/authors/16382592-ashwinraj-gnanaveltag:www.mathworks.com,2005:Question/4842662019-10-08T20:19:50Z2019-10-13T23:35:28ZError while reading image (.TIF)I have attached the segment of the main code (.mat) and the necessary function (get_TIF_raw_data2D) in .m format
The image is in .TIF format. When i ran the program with the image in .SPE format before ,i got the output. The output is it reads intensity of each pixel in the image.
Now, i want to run the program in .TIF format. But if i run in .TIF format ,i am getting an error stating that "Error using reshape
To RESHAPE the number of elements must not change".
Do I need to make any changes while running in the function while running in .TIF format. Can anyone help me out to debug the function so that I could get the ouput while running in .TIF format also?
Do I need to change the number of bits in the function code? Please help me out.
Maincode:
Ci_temp = 'c_init_notip.TIF';
Ci = get_TIF_raw_data2D(Ci_temp);
clear Ci_temp;
Ci_d = double(Ci);
clear Ci;
Ci_avg = mean(Ci_d, 3);
Function:
function [extracted_data header] = get_TIF_raw_data2D(filename)
fid=fopen(filename);
headersize=4100;
raw_data=[];
header = fread(fid,2050,'uint16=>uint16'); % 2050 uint16 = 4100 bytes = 32800 bits
Xdim = header(22); %raw_data_width %width as pixel number for each frame
Ydim = header(329); %raw_data_height % height as pixel number for each frame
Zdim = header(724); %
DataType = header(55);
if Zdim == 0
Zdim =1;
end
%Total_Size_XYZ = Xdim*Ydim*Zdim
%raw_data
switch DataType
case 0 % FLOATING POINT (4 bytes / 32 bits)
raw_data = fread(fid,inf,'float32=>float32');
case 1 % LONG INTEGER (4 bytes / 32 bits)
raw_data = fread(fid,inf,'int32=>int32');
case 2 % INTEGER (2 bytes / 16 bits)
raw_data = fread(fid,inf,'int16=>int16');
case 3 % UNSIGNED INTEGER (2 bytes / 16 bits)
raw_data = fread(fid,inf,'uint16=>uint16');
end
fclose(fid);
frame4view1 = reshape(raw_data,Xdim,Ydim,Zdim);
clear raw_data; %clear some memory
%permute the X and Y dimensions so that an image looks like in Winview
frame4view1 = permute(frame4view1,[2,1,3]);
extracted_data = frame4view1;
Ashwinraj Gnanavelhttps://www.mathworks.com/matlabcentral/profile/authors/16382592-ashwinraj-gnanaveltag:www.mathworks.com,2005:Question/4850842019-10-13T20:57:34Z2019-10-13T23:35:27Zode solvers 2nd order differential equationI want to use ode solver to solve a 2nd order differential equation of angular acceleration for a torque equal to=1,
i have 7 states for position and 7 states of angular velocity ,
how to represent it in a function and matrix form to solve it ?bassim hanyhttps://www.mathworks.com/matlabcentral/profile/authors/9114772-bassim-hanytag:www.mathworks.com,2005:Question/4850972019-10-13T22:38:12Z2019-10-13T23:34:12Zaudioplayer with jack?I am running matlab version 9.4.0.813654 (R2018a) on MX Linux 18 "Continuum". I have two RME Fireface 800 cards that I access with jack using ffado drivers. The cards work fine, eg., using portaudio they show up and are accessible as a single device. but they do not show up in Matlab using audiodevinfo. How can I play and record using these cards?Chris Brownhttps://www.mathworks.com/matlabcentral/profile/authors/8728216-chris-browntag:www.mathworks.com,2005:Question/4851002019-10-13T23:16:51Z2019-10-13T23:32:16ZHow to sort and save data in same workspace / excel?I have problem to save the data that i already sort by it Loading Port and Length. Im using for loop, the data that save in the final workpace is only the last sorted category, not the whole data.
data = readtable('Dummy.xlsx');
% LOADING
[Lport, a, LOADING] = unique(data(:,7));
LP = max(LOADING);
for G = 1 : LP
fprintf('\n\n\n\t\t\t\t\t\t\t\t\t <strong>LOADING PORT %d </strong>\n', G)
L = data(LOADING==G,:);
% display(data(LOADING==G,:))
[Length, b, LENGTH] = unique(L(:,3));
l = max(LENGTH);
for G = 1 : l
fprintf('\t\t\t\t\t\t\t\t\t<strong>LENGTH : Category %d</strong>\n',G)
length = L(LENGTH==G,:);
fprintf('\t\t\t\t\t\t\t\t\t <strong>SORTED WEIGHT</strong>\n')
[Weight, c] = unique(length.WEIGHT);
display(length(c,:))
end
end
The results in command window is here, but in workspace / variables on show the last loop / data.
LOADING PORT 1
LENGTH : Category 1
SORTED WEIGHT
NO CODE LENGTH HEIGHT WEIGHT SPECIAL LOADING UNLOADING
__ _________ ______ ______ ______ _______ _______ _________
1 'Alpha' 20 8 200 NaN 'AA' 'BB'
6 'Foxtrot' 20 8 222 NaN 'AA' 'BB'
2 'Bravo' 20 8 250 NaN 'AA' 'BB'
5 'Echo' 20 8 564 NaN 'AA' 'CC'
LENGTH : Category 2
SORTED WEIGHT
NO CODE LENGTH HEIGHT WEIGHT SPECIAL LOADING UNLOADING
__ _________ ______ ______ ______ _______ _______ _________
3 'Charlie' 40 8 360 NaN 'AA' 'BB'
4 'Delta' 40 8 950 NaN 'AA' 'CC'
LOADING PORT 2
LENGTH : Category 1
SORTED WEIGHT
NO CODE LENGTH HEIGHT WEIGHT SPECIAL LOADING UNLOADING
__ __________ ______ ______ ______ _______ _______ _________
10 'Juliet' 20 8 200 NaN 'BB' 'CC'
13 'Mike' 20 8 351 NaN 'BB' 'AA'
14 'November' 20 8 500 NaN 'BB' 'AA'
8 'Hotel' 20 8 569 NaN 'BB' 'CC'
9 'India' 20 8 752 NaN 'BB' 'CC'
LENGTH : Category 2
SORTED WEIGHT
NO CODE LENGTH HEIGHT WEIGHT SPECIAL LOADING UNLOADING
__ ______ ______ ______ ______ _______ _______ _________
12 'Lima' 40 8 245 NaN 'BB' 'AA'
7 'Golf' 40 8 248 NaN 'BB' 'CC'
11 'Kilo' 40 8 265 NaN 'BB' 'AA'
Here is the dummy data from the excel.Muhammad Shaiful Bahrihttps://www.mathworks.com/matlabcentral/profile/authors/15961834-muhammad-shaiful-bahritag:www.mathworks.com,2005:Question/4850922019-10-13T21:54:50Z2019-10-13T23:21:26ZFor loops and If statements not working correctlyHello,
I'm trying to plot a time to velocity graph where the velocity is calculated from 3 equations. The three equations are:
This is what my code looks like:
clc
clear
time = [0:0.1:25];
velocity = zeros(length(time),1);
for t = time
if t <= 5
velocity = 0.1553567*time.^6 - 2.0416*time.^5 + 9.1837*time.^4 - 14.829*time.^3 - 1.3703*time.^2 + 32.821*time - 1.3155;
elseif (5<t) && (t<=15.4)
velocity = 0.003980879*time.^5 - 0.2247*time.^4 + 4.8682*time.^3 - 50.442*time.^2 + 254.67*time - 430.66;
else
velocity = -0.073*time.^2 + 6.1802*time + 40.423;
end
end
plot(time,velocity)
For some reason all the time seems to go through the else statement. Can anyone please help me out, I've been struggling on this simple code for a while now. The graph should also look something similar to this:
Deepak Singhhttps://www.mathworks.com/matlabcentral/profile/authors/14794862-deepak-singhtag:www.mathworks.com,2005:Question/4850992019-10-13T22:49:09Z2019-10-13T23:21:25ZSummation of Random NumbersHow would you go about writing a code to solve a summations of randomly generated intergers, say r= to an equation, until the sum is greater than a number, say x.
Alyx Kalleberghttps://www.mathworks.com/matlabcentral/profile/authors/16558012-alyx-kallebergtag:www.mathworks.com,2005:Question/4850102019-10-13T10:52:39Z2019-10-13T23:17:25Zhow to find H(e j(ω π) ) if you know H(e j(ω), you found out H(e j(ω) by using freqzhow to find H(e j(ω +π) ) if you know H(e j(ω), you found out H(e j(ω) by using freqz
For instance, you have H(e(jw)) by having an array of h, and then you find out h(e^(jw)) by using [h,w]=freqz(h).But now I want to know how to find H(e^(jw+pi)). Thank you!
Anh Daohttps://www.mathworks.com/matlabcentral/profile/authors/14969988-anh-daotag:www.mathworks.com,2005:Question/4850912019-10-13T21:54:28Z2019-10-13T23:07:33ZHow to specify a number to the specified position in the array？Hi guys, the question is that now I used 'zeros' command, to create an array which have 20 positions, then there are some data will be created to fill the array, and I want to point data to the specified position. For example, the No.1 data should stay in the first position, the end data should stay in the second position, the No.2 data should stay in the third position. Is there any function can help me arrange their positions? Thanks a lot ! YANGCHENG LIULhttps://www.mathworks.com/matlabcentral/profile/authors/15512283-yangcheng-liultag:www.mathworks.com,2005:Question/4850822019-10-13T20:53:35Z2019-10-13T22:34:34Zmatlab function giving me error (In an assignment A(I) = B, the number of elements in B and I must be the same.) , How to solve this errorfunction qdot=func(dq,q)
tau = ones(7,1);
qdot(1) = dq;
qdot(2) = tau - get_CoriolisVector(q,dq) - get_GravityVector(q) - get_FrictionTorque(dq); %% error :In an assignment A(I) = B, the number of elements in B and I
must be the same
end
bassim hanyhttps://www.mathworks.com/matlabcentral/profile/authors/9114772-bassim-hanytag:www.mathworks.com,2005:Question/1594782014-10-21T09:16:39Z2019-10-13T22:33:50ZHow compare pixels from two images to find a match?I am having two images where second image is the warped image of previous one. Using random generator , I am selecting 8x8 pixels to compare both images and find the match(minimization function).
I am getting an error in fminunc
Error using fminunc (line 171)
FMINUNC requires the following inputs to be of data type double: 'X0'.
Error in mainsample (line 14)
[s fval] = fminunc(@myfun , subblock)
How do I go about it?
My code for generating random pixels are:
clear all;
close all;
I = rgb2gray(imread('testimage.jpg'));
original = rgb2gray(imread('testimage.jpg'));
original = double(original);
for( j = 0 : 1:7)
r = randi(225-7);
c = randi(225-7);
subblock = I(r:r+7, c:c+7);
imshow(subblock);figure;
t = [1 1];
[s fval] = fminunc(@myfun , subblock)
end
function f = myfun(x)
scale = 0.7;
J = imresize(x, scale);
theta = 30;
x0 = imrotate(J,theta);
for( i = 1:1:225)
f = (x^2 - x0(i)^2);
endEmmanuelhttps://www.mathworks.com/matlabcentral/profile/authors/4160343-emmanueltag:www.mathworks.com,2005:Question/4850772019-10-13T19:43:40Z2019-10-13T22:32:13ZHow to plot a lorentzian peak with known hwhm, position and height?Hi,
I would like to plot a graph to how the deconvolution of an FTIR spectrum. I've fitted the peaks with a separate program and I have the peak information for the individual peaks (hwhm, position and height).
There doesn't seem to be a simple lorentzian function on matlab as far as I can see?
Note: I am not trying to fit any data, I'm trying to plot stand alone lorentzian peaks to break down a spectrum.
I'm made the following function:
function y = lorentz(x, pos, h, H)
num = H*0.5;
den = ( x - pos ).^2 + (0.5 * H).^2;
y = h* num*(den.^-1)*(pi).^1;
end
and used the following code to plot it:
x = linspace (3100, 3700, 1000);
pos = 3624;
h = 0.7945223;
H = 2.003005*2;
d = lorentz(x, pos, h, H);
plot(x, d)
But the height of the function is not the correct height.Nuzhat Tabassumhttps://www.mathworks.com/matlabcentral/profile/authors/9146866-nuzhat-tabassumtag:www.mathworks.com,2005:Question/4850792019-10-13T19:53:23Z2019-10-13T22:27:23ZPlease help me !!! Error using * Inner matrix dimensions must agree. Error in GRAFICA_TOTAL_2 (line 40) Volum= (2*T.^2*q1+q2*T.^3*((1/2-(A1*(A2-A3))/2*C*Ro*G(A1+A2-A3))))clear;clc;
Ro=1; G=981; A1=100; A2=150; A3=125;
% *********************Hallando Desplazamiento**************************
CC = input ('Ingrese la COMPLIANCIA (cm3/cmH2O)DEL PULMON C = ')
subplot (2,2,1);syms t ;t=0:0.1:3; Q =(t+0.1*sin(8*t));
% stairs(t,Q); hold on % hold off
plot(t,Q)
legend('t+0.1*sin(8t)')
title ("FLUJO/CAUDAL Q, VARIANTE RESPECTO AL TIEMPO")
xlabel("Tiempo (seg)")
ylabel("Flujo ó Caudal en LPM")
% ***********************Hallando Aceleración***************************
C= CC/981;syms T
Q = (T+0.1*sin(8*T));
X=((C*Ro*G*Q*T*(A1+A2-A3)/C*Ro*G*A1*A3)-Q*T*A1*(A2-A3)/(C*Ro*G*A1*A3));
subplot(2,2,2);T=0:0.01:3; Acel= diff (X,2); % Derivada de segundo orden
Acel=double(subs(Acel)); % stairs(T,Acel);% hold off
hold on
plot(T,Acel)
title ("ACELERACIÓN RESPECTO AL TIEMPO ")
xlabel("Tiempo (seg)")
ylabel("Aceleracion en cm/seg2")
%*******************Hallando VOLUMEN****************************
C= CC/981; syms T
Q = (T+0.1*sin(8*T)); T=0:0.01:3;
q=double (subs(Q));
q1=diff(Q)
ql=double(subs(Q));
q2=diff (Q,2)
q2=double(subs(Q));
subplot (2,2,3)
% Volum = Acel*(T.^2/2)*((A1*A3)/(A1+A2-A3)); pretty (Volum);
Volum= (2*T.^2*q1+q2*T.^3*((1/2-(A1*(A2-A3))/2*C*Ro*G(A1+A2-A3))))
% Volum= T.^2+ T.^2*cos(T) - 0.5*sin(T.^4)
hold on
grid on
vol= eval (Volum)
plot(T,Vol)
%**************Hallando PRESIÓN******************
syms T
Q = (T+0.1*sin(8*T)); T=0:0.1:3;
Pres=(Volum*((A1+A2-A3)/A1- C*Ro*G(A1+A2-A3)-A1(A2-A3)/C*Ro*G*A1))/ A2-A3;
plot(t,Pres)
title ("PRESION CON RESPECTO AL TIEMPO ")
xlabel("Tiempo (seg)")
ylabel("Presión en cm-H2O")César Arturo Niño Carmonahttps://www.mathworks.com/matlabcentral/profile/authors/10475272-cesar-arturo-nino-carmonatag:www.mathworks.com,2005:Question/4850882019-10-13T21:31:51Z2019-10-13T22:12:23ZError inside of function using feval on user-provided polynomialHi all, I am having an issue with my code and I can't figure it out for the life of me. Here's my code:
function [l,r,nf] = bisect(fname,a,b,tol)
if(a == b)
if(feval(fname,a) == 0)
l = a;
r = l;
nf = 0;
return;
else
l = NaN;
r = l;
nf = -1;
return;
end
end
The error message states:
Error using feval
Function to evaluate must be represented as a string scalar, character vector, or function_handle object.
Error in bisect (line 26)
if(feval(fname,a) == 0).
Can anyone point me in the right direction? Help would be so much appreciated.Nicole Striplinghttps://www.mathworks.com/matlabcentral/profile/authors/9998377-nicole-striplingtag:www.mathworks.com,2005:Question/4850942019-10-13T22:08:33Z2019-10-13T22:11:06ZHow do I only take the first 1000 elements of a vector?My task is to use the first 1000 elements in a vector. So how do I only take the first 1000 elements of a vector? I am new to MATLAB, so any help would be appreciated. I tried finding a source to read about how to do this, but could not find one. Thank you!Anne Nguyenhttps://www.mathworks.com/matlabcentral/profile/authors/16054243-anne-nguyentag:www.mathworks.com,2005:Question/4849722019-10-13T00:30:18Z2019-10-13T22:09:04ZSuggestions for predicting the displacement of a graph or force estimation.Hello
This question is aimed mostly to engineers but whoever believes he can handle it may give his valuable advice.
I have a tabular data set of Load/Displacements in Newton/mm of a material using an Instron Machine, applying compressive forces.
Those data are my reference or gold standard. The same material is depicted on images where unknown forces are applied to the object and the object deforms as it is a rubber material. I want to estimate the forces caused that deformation.
My idea is developing a model that measures each column of the image that the object is depicted under strain. I measure the heigh of the object in each image column and find the difference from the gold standard that I have. Sounds simple right? I was thinking an interpolation method to bridge the gaps between the gold standard and the measured data from the images. E.g. if the gold standard data for 5 Newton is 2 mm displacement from its original position (undeformed material), then how many newtons are required to displace the same object at 5 mm from its original position. Something like that.
Can you help with suggestions and ideas please?
Thanks in advance
Stelios Fanourakishttps://www.mathworks.com/matlabcentral/profile/authors/10865530-stelios-fanourakistag:www.mathworks.com,2005:Question/4850872019-10-13T21:27:02Z2019-10-13T22:09:02ZFunction to check if a number is divisible by 5 How can I write a function m.file that takes as input a real number and checks to see if it is divisible by 5. An appropriate message indicating the result should be the output.
I have tried to write this but it dosen't seem to work as I need the user to input a number and check if it is divisble by 5
function [resp] = div5(x)
if (rem(x,5) == 0)
resp = 1;
else
resp = 0;
end
Thanks in advance
Paul Heymannhttps://www.mathworks.com/matlabcentral/profile/authors/16557833-paul-heymanntag:www.mathworks.com,2005:Question/4850892019-10-13T21:43:44Z2019-10-13T21:43:44ZExtracting 2 coloumns from diifferent excel files, and trying to plot them Hi all,
I'm trying to take 2 coloumns from a bunch of different excel sheets in my directory (all of them have same variables, just different values in each coloumn).
I want to plot the 2 coloumns and create individual plots for each sheet.
I have a code here that allows me to extract the two coloumns and plot it on the same plot, but it doesn't seem to be working.
Would someone be able to help me figure out why this isn't working? and what i can do to modify it so I can plot single plots for every excel sheet.
Code:
files = dir('*/*.xls');
for i=1:length(files)
data = xlsxread(files(i).name);
x=data(:,2);
y=data(:,3);
plot(x,y)
end
Veena Sanmugananthanhttps://www.mathworks.com/matlabcentral/profile/authors/15469617-veena-sanmugananthantag:www.mathworks.com,2005:Question/254302012-01-06T00:52:30Z2019-10-13T21:42:00ZSimMechanics Link ProblemI am trying to import a Solidowrks assembly into simMechanics. I followed all the steps as in the web site. I have the pull-down menu SinMechanics Link in SolidWorks. When I try to save the assembly in the xml format, I get this error:
Could not start MATLAB. Check your MATLAB installation. Consult documentation to identify possible causes of failure.
I get this error regarding Matlab is open or not.
Note: I am using Matlab 2010a and SolidWorks 2010Mohamed Trabiahttps://www.mathworks.com/matlabcentral/profile/authors/44491-mohamed-trabiatag:www.mathworks.com,2005:Question/4850732019-10-13T19:34:16Z2019-10-13T21:27:05ZRemove strings from an array based on string lengthHello. I'm trying to remove strings from a string array based on string length. I want to remove strings with lesser than 2 alphabets. I tried the following code but I'm getting an error
clc; clear;
s = {'a';'b';'cat';'apple'};
s1 = string(s);
String_length = strlength(s1);
Min_length = 2;
Modified_string = [s1 String_length];
indices = find(Modified_string(:,2) < Min_length);
Modified_string(indices,:) = [];
Error using <
Comparison between string and double is not supported.
Error in Dummy (line 8)
indices = find(Modified_string(:,2) < Min_length);Aravind Vicinthangal Prathivaathihttps://www.mathworks.com/matlabcentral/profile/authors/14269592-aravind-vicinthangal-prathivaathitag:www.mathworks.com,2005:Question/382552012-05-13T21:53:14Z2019-10-13T21:25:39ZDisplay USGS DEM using geotiffread and mapshowHi, I'm trying to use USGS DEMs in MATLAB but after reading it in with geotiffread, mapshow produces an error. Based on the documentation, I tried
[A, R] = geotiffread('NED_10340081')
figure
mapshow(A, R);
but I get
Error using mapshow
Expected input number 1, I or X or RGB, to be one of these types:
uint8, uint16, double, logical
Instead its type was single.
Error in validateMapRasterData>parseImageInputs (line 109)
validateattributes(A, {'uint8', 'uint16', 'double', 'logical'}, ...
Error in validateMapRasterData>validateImageComponent (line 93)
[A, R] = parseImageInputs(mapfcnname, dataArgs{:}, cmap, rules );
Error in validateMapRasterData (line 27)
[Z, SpatialRef] = validateImageComponent(mapfcnname, ...
Error in maprastershow (line 127)
[Z, SpatialRef, displayType, HGpairs] = ...
Error in mapshow (line 231)
h = showFcn(varargin{:});
My matrix A is of type single...is that the problem? and how do I fix this? ThanksDominikhttps://www.mathworks.com/matlabcentral/profile/authors/2997061-dominiktag:www.mathworks.com,2005:Question/4850862019-10-13T21:05:54Z2019-10-13T21:24:48ZHow do I call a function into another file? I have a function in a file called kguess.m that has this and produces the value for k
function k = kguess(w, g, h)
k = (w) / (g*sqrt(tanh((w)*h)/g));
end
But I am trying to use the ouput from the file kguess.m and plug it into equations within another file called my_function.m and I am not sure why I am getting errors. I have tried different methods but none seem to work. Could someone please help me?
g = 9.81;
H = input('Input a value for the variable H: ');
Ws = input('Input a value for the variable Ws: ');
k = [k];
for n = k:100
F = g.*k.*tanh(k.*H)-Ws;
FP = g.*(tanh(k.*H))+k.*(sech(k.*H).^2);
A = k - (F/FP);
k = k +1;
end
Ranger Quinterohttps://www.mathworks.com/matlabcentral/profile/authors/11980526-ranger-quinterotag:www.mathworks.com,2005:Question/4850782019-10-13T19:47:39Z2019-10-13T21:16:12ZNested Loop for 3D Matrix - Replace Values > 100 with 100Hi,
I have a problem regarding a 3D matrix and using a nested loop to replace values larger than 100 with 100. The question is as follows.
Write a nested for loop that checks all the values in matrix and set them to 100 if they are larger than 100.
Res_K(:,:,1) = [100 90 75 80; 40 110 70 65; 80 80 103 95];
Res_K(:,:,2) = [95 55 40 100; 90 75 80 104; 110 70 65 80];
Res_K(:,:,3) = [102 65 80 80; 71 90 75 108; 40 110 79 95];
I = size(Res_K, 1);
J = size(Res_K, 2);
K = size(Res_K, 3);
Kylar Rodehttps://www.mathworks.com/matlabcentral/profile/authors/15215285-kylar-rodetag:www.mathworks.com,2005:Question/4850832019-10-13T20:55:03Z2019-10-13T21:06:21ZWhy, Array indices must be positive integers or logical valuesP=450000
r=0.042
M=P(r/12)
Error array indices must be positive or logical values.
Can someone please help me
Why is it saying thisPenuel Adiyiahhttps://www.mathworks.com/matlabcentral/profile/authors/16328795-penuel-adiyiahtag:www.mathworks.com,2005:Question/4849902019-10-13T05:44:57Z2019-10-13T20:39:44ZProblem while opening the imageAfter I save .tiff file from winspec and if I open it the image gets darker and consequently if i read them through matlab, I get very less intensity values. I am not getting the correct intensity values since it is dark. It is a 16 bit image .Ashwinraj Gnanavelhttps://www.mathworks.com/matlabcentral/profile/authors/16382592-ashwinraj-gnanaveltag:www.mathworks.com,2005:Question/4850372019-10-13T14:02:20Z2019-10-13T20:39:41Zmissing values after re-grid using gridinterpolant ! how to prevent?I was regriding a NetCDF file using this code below. All is fine, but there are missing values in my selected range of latitude and longitude after regridding while there are no missing values in original data along with this selected range of latitude and longitude. how to fix this issue? I have attached the output files (before and after regrid) as an image. first is before regrid that you can see all across the country have value but after regrid, some part of north and center are in white that means they don't have any values.
I want to achieve an output after regriding all over the boundary. how to do it? how to fix the problem?
clc
clear
format compact
close all
filename='precip.mon.total.v2018.nc'; %my netcdf file name
ncdisp(filename)
lat = ncread(filename,'lat');
lon = ncread(filename,'lon');
precip = ncread(filename,'precip');
t = ncread(filename,'time');
index=find(precip==-9.969209968386869e+36);
precip(index)=NaN;
lat=double(lat);
lon=double(lon);
precip=double(precip);
t=double(t);
ds = 0.25 ;
loni = min(lon):ds:max(lon);
lati = min(lat):ds:max(lat);
ind1 = find(loni>=44 & loni<=64);
ind2 = find(lati>=24 & lati<=40);
lati = lati(ind2);
loni = loni(ind1);
[Loni,Lati] = meshgrid(loni,lati);
F=griddedInterpolant({lon,flip(lat),t},flip(precip,1));
newpreceip=F({loni,lati,t});
ncdisp is:
Source:
F:\MATLAB WORKS\code desktops\precip.mon.total.v2018.nc
Format:
netcdf4_classic
Global Attributes:
Original_Source = 'http://www.dwd.de/en/FundE/Klima/KLIS/int/GPCC/GPCC.htm
is the webpage and the data is at ftp://ftp.dwd.de/pub/data/gpcc/download.html'
Reference = 'Users of the data sets are kindly requested to give feed back and to refer to GPCC publications on this webpage: http://www.dwd.de/bvbw/appmanager/bvbw/dwdwwwDesktop/?_nfpb=true&_pageLabel=_dwdwww_klima_umwelt_datenzentren_wzn&T12404518261141645246564gsbDocumentPath=Content%2FOeffentlichkeit%2FKU%2FKU4%2FKU42%2Fteaser__product__access.html&_state=maximized&_windowLabel=T12404518261141645246564&lastPageLabel=_dwdwww_klima_umwelt_datenzentren_wzn'
original_source = 'ftp://ftp-anon.dwd.de/pub/data/gpcc/html/fulldata_download.html'
Conventions = 'CF 1.0'
dataset_title = 'Global Precipitation Climatology Centre (GPCC)'
References = 'https://www.esrl.noaa.gov/psd/data/gridded/data.gpcc.html'
title = 'GPCC Full Data Reanalysis Version 2018 0.5x0.5 Monthly Total'
history = 'Created 09/2018 based on V2018 data obtained via ftp'
data_modified = '2019-03-12'
_NCProperties = 'version=2,netcdf=4.6.3,hdf5=1.10.5'
Dimensions:
lat = 360
lon = 720
nbnds = 2
time = 1512 (UNLIMITED)
Variables:
lat
Size: 360x1
Dimensions: lat
Datatype: single
Attributes:
long_name = 'Latitude'
units = 'degrees_north'
standard_name = 'latitude'
axis = 'Y'
coordinate_defines = 'point'
actual_range = [89.75 -89.75]
lon
Size: 720x1
Dimensions: lon
Datatype: single
Attributes:
long_name = 'Longitude'
units = 'degrees_east'
standard_name = 'longitude'
actual_range = [0.25 359.75]
axis = 'X'
coordinate_defines = 'point'
time
Size: 1512x1
Dimensions: time
Datatype: double
Attributes:
long_name = 'Time'
units = 'days since 1800-1-1 00:00:00'
delta_t = '0000-01-00 00:00:00'
avg_period = '0000-01-00 00:00:00'
standard_name = 'time'
axis = 'T'
coordinate_defines = 'start'
actual_range = [33237 79227]
precip
Size: 720x360x1512
Dimensions: lon,lat,time
Datatype: single
Attributes:
missing_value = -9.969209968386869e+36
units = 'mm'
var_desc = 'Precipitation'
level_desc = 'Surface'
parent_stat = 'Observations'
long_name = 'GPCC Monthly total of precipitation'
valid_range = [0 8000]
statistic = 'Total'
level = 'Surface'
actual_range = [0 4552.4302]
dataset = 'GPCC Precipitation 0.5degree V2018 Full Reanalysis
Please Help me to overcome this issue. Any suggestions are appreciated! Thank you!Behzad Navidihttps://www.mathworks.com/matlabcentral/profile/authors/15525777-behzad-naviditag:www.mathworks.com,2005:Question/4850812019-10-13T20:34:31Z2019-10-13T20:34:31ZHow can a variable be defined for plotting transfer functions in s-domain and t-domain at the same time? I have a closed loop feedback system with multiple inputs (such as one reference and another disturbance signal), a controller has been added as some sort of compensator to make it stable, I have been able to plot root locus for this system(in s-domain) to see its stability region.
How can I see trends of either of input versus the system's output or any signal that comes in between? Should I convert the parameters to time domain or I can plot these without change of domain or assigning variables separately?Rabia M.https://www.mathworks.com/matlabcentral/profile/authors/14368366-rabia-mtag:www.mathworks.com,2005:Question/4850802019-10-13T20:16:27Z2019-10-13T20:16:27ZDivide and transform frequency bands to fourier transformHello, I have a wav file such as this.
[y,fs,wmode,fidx]=readwav('data/piano.wav'); %fs/sampling frequency = 16000; length = 176000
How would I, for every part of 512 samples, transform 8 frequency bands (such as [0Hz,1kHz), [1kHz, 2kHz), and so on) in the Fourier transformed signal?Rayan Suryadikarahttps://www.mathworks.com/matlabcentral/profile/authors/16493083-rayan-suryadikaratag:www.mathworks.com,2005:Question/4722342019-07-17T20:50:52Z2019-10-13T19:55:04ZHow can I extract the frame around the windows?Hello,
I need to extract the frame on the wall around the window. How can I do that? I have tried with edge detection and binarization, but I have got always a different result. There are images, where even the edges are not recognizable. But, there are images full with different edges where I can not eliminate the redundant components.
I hope someone can help me.
Thank you.Lhttps://www.mathworks.com/matlabcentral/profile/authors/3290037-ltag:www.mathworks.com,2005:Question/4850692019-10-13T19:02:00Z2019-10-13T19:49:21ZHow to 'clean' data using moving average window filter
How would I go about 'cleaning' the data by using a moving average window filter, using a window size of 5 and plotting this part in a new figure. I added the line of code y2 = movmean(y,5) but it is not giving me the results I need. Thank you in advance. timetry2https://www.mathworks.com/matlabcentral/profile/authors/14876308-timetry2tag:www.mathworks.com,2005:Question/4850612019-10-13T18:10:08Z2019-10-13T19:48:43ZHow can I find the value with the most change in my histogram?
[N,edges] = histcounts(Y);
min = mean();
[k1,k2,k3]=size(imYuv) %Size of the picture
for i=1:k1
for j=1:k2
if Y(i,j)>min
Y(i,j)=0;
end
end
end
imYuv(:,:,1)=Y;
final = colorspace('RGB<-YUV',imYuv);
I know the value is around .64 something.
But im trying to automated so it can select that for my threshold value.ThatStudenthttps://www.mathworks.com/matlabcentral/profile/authors/16026654-thatstudenttag:www.mathworks.com,2005:Question/4839682019-10-07T10:36:37Z2019-10-13T19:45:52ZFind cycles in an undirected graphHi, I need to find cycles in a graph, exactly as it was asked here (and apparently without fully clear/working solutions!):
find cycle in array https://ch.mathworks.com/matlabcentral/answers/425321-find-cycle-in-array
find a cycles in undirected graph https://ch.mathworks.com/matlabcentral/answers/421435-find-a-cycles-in-undirected-graph
Here my example/code:
clear all; clc; close all;
figure('Color',[1 1 1]);
s = [1 1 1 2 3 3 4 4 5 6 7 6 8 9 10 10 12 12 13 14 15 16 17 17 18 19 20 21 20 25];
t = [2 8 18 3 4 23 5 21 6 7 8 11 9 10 11 12 14 13 15 18 16 17 18 25 19 20 1 22 24 26];
G = graph(s,t);
x = [0.5 0 0 0 0.5 1 1.5 2 3 3 3 5.5 6 4 6 6 4 3 2 0.5 -1 -2 -1 1.5 4.5 4.5];
y = [0 0.5 1 1.5 2 2 1.5 1 1 1.5 2 1 0.5 0.5 0 -1 -1 -0.5 -1 -1 1 0.5 0.5 -0.5 -0.5 0];
h = plot(G,'XData',x,'YData',y,'linewidth',2,'MarkerSize',7);
nl = h.NodeLabel;
h.NodeLabel = '';
xd = get(h, 'XData');
yd = get(h, 'YData');
text(xd, yd, nl, 'FontSize',17, 'FontWeight','bold', ...
'HorizontalAlignment','left', 'VerticalAlignment','top')
set(gca,'Fontsize',15,'FontWeight','Bold','LineWidth',2, 'box','on')
% Remove "branches"
xy = [x' y'];
while ~isempty(find(degree(G)==1))
degreeone = find(degree(G)==1);
G = rmnode(G,degreeone);
xy(degreeone,:) = [];
end
Here the corresponding Figure (after removal of "branches"):
My goal would be to find the following 5 cycles as output (i.e. lists of nodes composing each cycle):
1-2-3-4-5-6-7-8-1
6-7-8-9-10-11-6
1-8-9-10-12-14-18-1
1-18-19-20-1
12-13-15-16-17-18-14-12
Note 1:
This is the Sergii Iglin 's idea, that I found in https://ch.mathworks.com/matlabcentral/fileexchange/4266-grtheory-graph-theory-toolbox
This method is partially working for my purposes.
Unfortunately, the 2nd and 4th cycles are not what I needed/expected.
% Sergii Iglin
% https://iglin.org/All/GrMatlab/grCycleBasis.html
E = table2array(G.Edges);
Output_SI = grCycleBasis(E);
% [my part] From the Sergii Iglin's output to cycles nodes
for i = 1 : size(Output_SI,2)
w = [];
u = E(find(Output_SI(:,i)),:); % edges list
w(1) = u(1,1);
w(2) = u(1,2);
u(1,:) = [];
j = 2;
while ~isempty(u)
[ind,~] = find(u==w(j));
[~,ind2] = ismember(u, u(ind,:), 'rows');
g = u( ind2==1 ,:) ~= w(j);
w(j+1) = u( ind2==1 , g);
u( ind2==1 ,:) = [];
j = j + 1;
end
cycles_SI{i} = w;
end
% Sergii Iglin's results
>> cycles_SI{:}
1 2 3 4 5 6 7 8 1
1 2 3 4 5 6 11 10 9 8 1
1 8 9 10 12 14 18 1
1 8 9 10 12 13 15 16 17 18 1
1 18 19 20 1
Note 2:
This is the Christine Tobler 's idea that I found in https://ch.mathworks.com/matlabcentral/answers/353565-are-there-matlab-codes-to-compute-cycle-spaces-of-graphs
This method is partially working for my purposes.
Unfortunately, the 2nd and 4th cycles are not what I needed/expected.
% Christine Tobler
% https://ch.mathworks.com/matlabcentral/answers/353565-are-there-matlab-codes-to-compute-cycle-spaces-of-graphs
t = minspantree(G, 'Type', 'forest');
% highlight(h,t)
nonTreeEdges = setdiff(G.Edges.EndNodes, t.Edges.EndNodes, 'rows');
cycles_CT = cell(size(nonTreeEdges, 1), 1);
for i = 1 : length(cycles_CT)
src = nonTreeEdges(i, 1);
tgt = nonTreeEdges(i, 2);
cycles_CT{i} = [tgt shortestpath(t, src, tgt)];
end
% Christine Tobler's results
>> cycles_CT{:}
8 7 6 5 4 3 2 1 8
11 10 9 8 1 2 3 4 5 6 11
18 14 12 10 9 8 1 18
18 17 16 15 13 12 10 9 8 1 18
20 19 18 1 20
Note 3:
Methods from Sergii Iglin and Christine Tobler give the same result!
Note 4:
The ideas / FileExchange submissions
Count all cycles in simple undirected graph version 1.2.0.0 (5.43 KB) by Jeff Howbert
Count Loops in a Graph version 1.1.0.0 (167 KB) by Joseph Kirk
kindly suggested here
https://ch.mathworks.com/matlabcentral/answers/425321-find-cycle-in-array
are not working for my case...
Any further idea / suggestion ?
Thanks a lot!
Simone Loretihttps://www.mathworks.com/matlabcentral/profile/authors/14233052-simone-loreti