https://es.mathworks.com/matlabcentral/answers/questions.atomMATLAB Answers — New Questions2019-03-24T09:28:51Ztag:es.mathworks.com,2005:Question/4520032019-03-24T09:28:51Z2019-03-24T09:28:51Zkeep index of omited arrayA={[1,2,3,4,5],[1,3],[1],[1,3,4,5,6,7,89,0],[1,3],[1,3,4,5],[4,6]};
N = cellfun(@length,A) ;
A(N==2) = [];
I want to have index of length 2
result=[2,5,7]
I use this code but have error
index = cellfun(@(m) find(m(N==2)),A,'uni',0);
Naimehttps://es.mathworks.com/matlabcentral/profile/authors/13711668-naimetag:es.mathworks.com,2005:Question/4519792019-03-24T04:12:36Z2019-03-24T09:26:51ZMatlab Text file I/oWrite a function called char_counter that counts the number of a certain character in a text file. The function takes two input arguments, fname, a char vector of the filename and character, the char it counts in the file. The function returns charnum, the number of characters found. If the file is not found or character is not a valid char, the function return -1. As an example, consider the following run. The file "simple.txt" contains a single line: "This file should have exactly three a-s..."
charnum = char_counter('simple.txt','a')
charnum =
3Priyamvada Shankarhttps://es.mathworks.com/matlabcentral/profile/authors/15104143-priyamvada-shankartag:es.mathworks.com,2005:Question/4520012019-03-24T08:50:34Z2019-03-24T09:24:29Z code running for infinite while plotting my array for correlation Hi,
I have problem as my code running for infinite time while I am plotting my arrays to achive coeffcient correlation.
here is my code:
for i=1:length(A)-300
Rx{i}= corrcoef(A (i:i+300), S(i:i+300));
Time_Rx=i;
B{1,i} = Rx(i)
C{1,i} = Time_Rx
end
(Aiming for plot Rx as a function over time)
plotting by using:
plot(B,C);
Can not figure out what is wrong, Any help would be appriciable. Bobhttps://es.mathworks.com/matlabcentral/profile/authors/13187274-bobtag:es.mathworks.com,2005:Question/4519972019-03-24T08:12:20Z2019-03-24T09:21:29Zwhy my matlab can not surpport Advantech PCI-1714UL, and I add some information into mwAdvantehch.ini, but it did not work.whyA my matlab can not surpport Advantech PCI-1714UL, and I add some information into mwAdvantehch.ini, but it did not work.skong zhanghttps://es.mathworks.com/matlabcentral/profile/authors/4920582-skong-zhangtag:es.mathworks.com,2005:Question/4520022019-03-24T09:17:39Z2019-03-24T09:17:39ZWrap in a legend with num2strHi everyone!
I'm dealing with probability density functions.
In each figure i create i would like to add to legend the mean, the standard deviation and the cov (coefficient of variation). To do that i'm using the command num2str.
My code is:
%%
Excel_Caramagnabridge=load('caramagna.txt');
af_Caramagnabridge=Excel_Caramagnabridge(:,13);
Cover_Caramagna=Excel_Caramagnabridge(:,12);
CaramagnaEdges=3:0.3:12;
[Caramagna_mean, Caramagna_std]=normfit(af_Caramagnabridge);
Caramagna_cov=Caramagna_std/Caramagna_mean;
Caramagna_distr=normpdf(CaramagnaEdges,Caramagna_mean,Caramagna_std);
testCaramagna=chi2gof(Caramagna_distr);
figure; CaramagnaHist=histogram(af_Caramagnabridge,CaramagnaEdges,'Normalization','pdf');
hold on; f1=plot(CaramagnaEdges, Caramagna_distr, 'linewidth',2, 'color','b'); grid on;
legend([f1],['\mu = ' num2str(round(Caramagna_mean,2)) ' \sigma = ' num2str(round(Caramagna_std,2))], 'orientation','vertical',...
'location','northeast');
If i write in this way, the figure will report mean and std in a row. I just would like to wrap for each statistics.
How to do that?
Thanks!
Gianluca Borgnahttps://es.mathworks.com/matlabcentral/profile/authors/11591968-gianluca-borgnatag:es.mathworks.com,2005:Question/4519922019-03-24T07:04:09Z2019-03-24T08:57:57ZCreating a player vs AI dice gameSo my objective is to make a script that can play the game farkle with multiple human players and computer players however im having an error showing up in my script when it becomes the computer players turn and im not sure how ill be able to fix it. This is what I have so far:
Any help would be appreciated
clc;
clear;
rng('shuffle');
HP=input('Enter the number of HUMAN players:');
HumanPlayers=round(HP,0);
if (HumanPlayers<=0)
HumanPlayers=0;
end
CP=input('Enter the number of AI players:');
ComputerPlayers=round(CP,0);
if (ComputerPlayers<=0)
ComputerPlayers=0;
end
TotalPlayers = (ComputerPlayers + HumanPlayers);
TPVec = [TotalPlayers:-1:1];
TotalGameScore = zeros(size(TPVec)); %Makes the Zero Vector
tsVec = [TotalPlayers:-1:1];
TurnScore = zeros(size(tsVec));
PVec = [TotalPlayers:-1:1];
PT = zeros(size(PVec)) .* 1; % Player Turn Amount
PT = PT + 1;
%fprintf('\nTurn Number: %d \n', turn);
LC1 = 1;
%%
while (TotalPlayers>0 && max(TotalGameScore)<10000)
if (LC1 > TotalPlayers)
LC1 = 1;
end
%PT(LC1) = PT(LC1) + 1;
%fprintf('\nTurn Number: %d \n', PT(LC1));
fprintf('\n\n***** Player number: %d *****\n',LC1);
TS1 = 1;
while(TS1 ~= 0)
if (LC1 > TotalPlayers)
LC1 = 1;
end
if( LC1 <= HumanPlayers )
choice = input('\nRoll or Pass? Please make your selection:\n ','s');
if (choice == 'r' || choice == 'R')
choice = 'r';
elseif (choice == 'p' || choice == 'P')
choice = 'p';
else
fprintf('That doesnt work for me \n');
score = 100;
end
else
choice =(TotalGameScore(LC1):TurnScore(LC1):TotalGameScore);
fprintf('\nComputer player %d decides to select %s.\n',LC1,choice);
end
if choice == 'r'
Roll = randi(6,1,6);
fprintf('---Player %d rolled!---\n',LC1);
fprintf('*******Dice Values*******:\n')
fprintf('%6.0f\t',Roll)
fprintf('\n')
SortRoll=sort(Roll);
fprintf('*******Sorted Dice Values*******:\n')
fprintf('%6.0f\t',SortRoll)
fprintf('\n')
DiceKeep=input('Enter the dice number that you wish to keep:');
Rollnew=randi(6,1,(6-DiceKeep));
SortRollnew=sort(Rollnew,'descend');
fprintf('*******New Sorted Dice Values*******\n')
fprintf('%6.0f\t',SortRollnew)
fprintf('\n')
NewNumberOfDice=6-DiceKeep; %This subtracts the amount of dice chosen from the amount of dice available
disp('*******Number of dice available*******')
fprintf('%4.0f\n',NewNumberOfDice)
if NewNumberOfDice==0
disp('All 6 dice have been set aside, the player can roll 6 dice again!')
NumberOfDice=6;
end
TurnScore=input('Enter the score of this roll:');
if TurnScore == 0
PT(LC1) = PT(LC1) + 1;
TurnScore(LC1) = 0;
fprintf('\nCurrent turn is over with no score. Moving to next player.');
fprintf('\nPlayer %d game score is %d!',LC1,TotalGameScore(LC1));
LC1 = LC1 + 1;
TS1 = 0;
else
TurnScore(LC1) = TurnScore(LC1);
fprintf('\nPlayer %d accumulated %d points for this turn so far...',LC1,TurnScore(LC1));
end
else
PT(LC1) = PT(LC1) + 1;
TotalGameScore(LC1) = TotalGameScore(LC1) + TurnScore(LC1);
fprintf('Player %d accumulated %d points for this turn so far...',LC1,TurnScore(LC1));
TurnScore(LC1)=0;
fprintf('\nPlayer %d game score is %d!',LC1,TotalGameScore(LC1));
fprintf('\nTurn Number: %d \n', PT(LC1));
LC1 = LC1 + 1;
TS1 = 0;
end
% fprintf('\nYour total game score is %d!',TotalGameScore(LC1));
end
endWilliam Plummerhttps://es.mathworks.com/matlabcentral/profile/authors/14634672-william-plummertag:es.mathworks.com,2005:Question/4520002019-03-24T08:37:45Z2019-03-24T08:46:38ZHow find coordinate 'x', when i have coordinate 'y'?Hello all,
I have a problem with find coordinate 'x', when i have coordinate 'y'.
Did anyone have a similar problem?
Best RegardsPawel Podlewskihttps://es.mathworks.com/matlabcentral/profile/authors/9204513-pawel-podlewskitag:es.mathworks.com,2005:Question/4517512019-03-22T17:24:31Z2019-03-24T08:45:34ZCreate an accurate boundary around 2D point cloud horizontal planeHello everyone,
I am dealing with creating an accurate boundary (concave hull) of a point cloud. I want to create the a polygon around it and compute the center of gravity using centroid function. None of the threshold values (0-1) give me a good result. I add here a resulting boundary colored in blue and the point cloud set colored in red. Is there any better approach using another function rather then boundary+polyshape??
Alexandru Mihai LAPADAThttps://es.mathworks.com/matlabcentral/profile/authors/13426605-alexandru-mihai-lapadattag:es.mathworks.com,2005:Question/4517262019-03-22T15:22:12Z2019-03-24T08:42:08ZWrite a function called under_age that takes two positive integer scalar arguments: age that represents someone's age, and limit that represents an age limit. The function returns true if the person is younger than the age limit. If the second argfunction too_young = under_age(age,limit)
limit = 21
if age <= limit
too_young = true;
elseif age >= limit
too_young = false;
else
fprintf('invalid\n')
end
Abhishek singhhttps://es.mathworks.com/matlabcentral/profile/authors/14995171-abhishek-singhtag:es.mathworks.com,2005:Question/4519992019-03-24T08:35:50Z2019-03-24T08:35:50Zhow to car following model programing in matlab? or i need to simullink?how to car following model programing in matlab? or i need to simullink? i want to using gipps car following model,but i dont know how to programming in matlab and simullink?
how to lane changing model programming in matlab? (ANN model or multinomial logit model)reza karimihttps://es.mathworks.com/matlabcentral/profile/authors/15117816-reza-karimitag:es.mathworks.com,2005:Question/4512452019-03-20T18:27:25Z2019-03-24T08:26:00Zi want to find the transpose of the matrix m but showing error. please can anyone help with the errorfunction [m]=calc_m()
m_rot()=@(w) [0;cos(w);sin(w)];
Q=[0.4082,0.4082,-0.8165;0.7017,-0.7071,0;0.5774,0.5774,0.5774];
m()=@(w) Q*m_rot();
z=m.'sadgun pulagamhttps://es.mathworks.com/matlabcentral/profile/authors/15092486-sadgun-pulagamtag:es.mathworks.com,2005:Question/4519962019-03-24T08:08:48Z2019-03-24T08:08:48Zcan anyone sign up in Think speaki am having error while singing up the Think Speak, so we need any additional requirement for log in.D KUSHAL KUMARhttps://es.mathworks.com/matlabcentral/profile/authors/11645873-d-kushal-kumartag:es.mathworks.com,2005:Question/4519952019-03-24T08:05:32Z2019-03-24T08:05:32ZTimestamp on excel after pushing push buttonHi All,
i wish to record the time of every single click on the pushbutton into an excel sheet, how can i do this ?
Thanks in advance.Rae Cheonghttps://es.mathworks.com/matlabcentral/profile/authors/14030620-rae-cheongtag:es.mathworks.com,2005:Question/4503172019-03-15T18:16:37Z2019-03-24T07:53:34Zhow can i plot the following text files?im trying to plot the textfiles attached like the image attached, can anyone help me please?
ciaran balfehttps://es.mathworks.com/matlabcentral/profile/authors/14760963-ciaran-balfetag:es.mathworks.com,2005:Question/4446722019-02-13T05:44:54Z2019-03-24T07:52:00ZImplement code for multi range of temperature Hi
I need to execute and plot the below code for range of temperatures (T) instead of one value (T=333)
exampel range of T value between 310 and 350 with 5 incremental steps
clc; clear all; close all;
T =333;
Tc = 369.8;
Tr = T/Tc;
Vr = linspace(0.5,5,500);
funcPr = @(Vr) 8/3 * Tr./(Vr - 1/3) - 3./(Vr.^2);
Pr = funcPr(Vr);
if Tr < 1
Pr_l = 1.0;
vdW_Pr_l = [1 -1/3*(1+8*Tr/Pr_l) 3/Pr_l -1/Pr_l];
v=sort(roots(vdW_Pr_l));
A1 = (v(2)-v(1))*Pr_l - integral(funcPr,v(1),v(2));
A2 = integral(funcPr,v(2),v(3)) - (v(3)-v(2))*Pr_l;
AreaDiff = abs (A1-A2);
while AreaDiff > 0.0001
vdW_Pr_l = [1 -1/3*(1+8*Tr/Pr_l) 3/Pr_l -1/Pr_l];
v=sort(roots(vdW_Pr_l));
funcPr = @(Vr) 8/3 * Tr./(Vr - 1/3) - 3./(Vr.^2);
A1 = (v(2)-v(1))*Pr_l - integral(funcPr,v(1),v(2));
A2 = integral(funcPr,v(2),v(3)) - (v(3)-v(2))*Pr_l;
AreaDiff = abs (A1-A2);
Pr_l = Pr_l - 0.00001;
end
end
% Plot
plot(Vr,Pr); hold all
xlim([0.25 4])
ylim([-0.5 2])
xlabel('Vr')
ylabel('Pr')
plot([0.25 4],[Pr_l Pr_l],'k--')
plot(v(1),Pr_l,'bo',v(2),Pr_l,'bo',v(3),Pr_l,'bo')Ahmad AlJuhanihttps://es.mathworks.com/matlabcentral/profile/authors/11939015-ahmad-aljuhanitag:es.mathworks.com,2005:Question/4519942019-03-24T07:50:43Z2019-03-24T07:50:43ZImage processing structural Tensor EquationCAn anyone pls help me, How to calculate structural tensor matrix H for a given RGB image. Herewith i had attatche the equation.Priya Srihttps://es.mathworks.com/matlabcentral/profile/authors/14907648-priya-sritag:es.mathworks.com,2005:Question/4517212019-03-22T15:05:07Z2019-03-24T07:47:34Zloop in realtime arduino readingHi
I want to read a value of the variable each 0.02 seconds I write this code:
c(1)=readCount(encoder);
for i=2:100
c(i)=readCount(encoder)
pause(0.02)
end
actually I want to read the count of the encoder for the loop (i=2:100)
each 0.02 secound
john whitehttps://es.mathworks.com/matlabcentral/profile/authors/10514494-john-whitetag:es.mathworks.com,2005:Question/4458842019-02-19T18:58:24Z2019-03-24T07:44:33ZSave/Convert large number of figuresSo I have large number of .fig in a certain file directory. I'd like to save/convert all of them to .eps (I need high quality plots for publication). Is there anyway to do this without having to manually open every single .fig file and save it to a file with the same name but in .eps format? Preferably all the .eps files will be saved in a new folder called 'eps'.
Thanks a lot for your help guys!Anshhttps://es.mathworks.com/matlabcentral/profile/authors/7544404-anshtag:es.mathworks.com,2005:Question/4457882019-02-19T10:42:25Z2019-03-24T07:38:58ZError plot Bar graph Hi MATLAB community,
I am trying create a bar graph, but show the follows error message:
X = table2array(valoresextremos); % size matriz (27,2)
x = X(:,1); 27 lines
y = X(:,2); 27 lines
bar(x,y)
Error using bar (line 191)
XData values must be unique.
Error in valores_extremos_grafico (line 4)
bar(x,y)
Could help me ?
Thank
Guilherme Guilherme Lopes de Camposhttps://es.mathworks.com/matlabcentral/profile/authors/8623554-guilherme-lopes-de-campostag:es.mathworks.com,2005:Question/4518372019-03-23T07:36:58Z2019-03-24T07:33:32ZNumerical Solution for Matrix Differential EquationI am trying to solve the following differential equation:
where matrix Y is the desired solution, and A is a known matrix. The matrix sizes can be up to 8x8.
To check that MATLAB accepts a matrix ODE, I tried the following codes for the simplest case of 2x2 matrix and a constant A:
A=[1, 2; -1, -2];
ode_func =@ (X) -X*X-A;
Y0 = [1, 1; 1, 1]; T0=0; Tf=100;
Y=zeros(2,2);
[T,Y] = ode45(@(t,y) ode_func(y), [T0,Tf], Y0);
But it returns the error:
Error using *
Inner matrix dimensions must agree.
Error in =@ (X) -X*X -A
Error in @(t,y)ode_func(y)
Error in odearguments (line 88)
f0 = feval(ode,t0,y0,args{:}); % ODE15I sets args{1} to yp0.
Error in ode45 (line 114)
[neq, tspan, ntspan, next, t0, tfinal, tdir, y0, f0, odeArgs, odeFcn, ...
It seems the codes are not working. So, I am wondering whether MATLAB is able to solve a matrix ODE?
Thank you,Ramtin Taherihttps://es.mathworks.com/matlabcentral/profile/authors/10383230-ramtin-taheritag:es.mathworks.com,2005:Question/4454052019-02-17T12:52:49Z2019-03-24T07:33:15ZAssignment question based on excel file I/O Write a function called get_distance that accepts two character vector inputs representing the names of two cities. The function returns the distance between them as an output argument called distance. For example, the call get_distance('Alexandria, VA' , 'Allentown, PA') should return 195
. If one or both of the specified cities are not in the file, the function returns -1.
The code I tried is the following:
I get error in the " if text{i,1} == a" and "if text{1,j} == b" lines stating matrix dimensions must agree. Will be really helpful if someone can help me with it.
function distance = get_distance(a,b)
[~,text,raw] = xlsread('Distances.xlsx');
for i = 2 : size(text,1)
if text{i,1} == a
for j = 1 : size(text,2)
if text{2,j} == b
distance = raw{i,j};
else
distance = -1;
end
end
else
distance = -1;
end
endAjai Kannanhttps://es.mathworks.com/matlabcentral/profile/authors/14615080-ajai-kannantag:es.mathworks.com,2005:Question/3245792017-02-12T11:47:33Z2019-03-24T07:23:28Zhow can i draw graph of z^2=x^2-y^2 on matlab<<http://mathworks.com/matlabcentral/images/surf.gif>>Rabia Kanwalhttps://es.mathworks.com/matlabcentral/profile/authors/9709704-rabia-kanwaltag:es.mathworks.com,2005:Question/4519932019-03-24T07:21:35Z2019-03-24T07:21:35ZFFT filtering noise?why i didt get final signal like first sigal after denoise??
filename = 'koo.CSV';
M = csvread(filename);
x=M(:,3);
Y=M(:,4);
fs=250;
f=10;
subplot(3,2,1)
plot (x,Y,'b','linewidth',2)
title('Original Arc Signal')
xlabel('TIME,t(s)')
ylabel('VOLTAGE,V');
yrand = (rand(size(Y))-0.5) * 10;
z=Y + yrand;
subplot(3,2,2)
plot (x, z,'b', 'linewidth', 2)
title('Noisy Arc Signal')
xlabel('TIME,t(s)')
ylabel('VOLTAGE,V');
L=length(z);
NEFT=2^nextpow2(L);
z_fft=abs(fft(z,NEFT));
freq=fs/2*linspace(0,1.5,NEFT/2+1);
subplot(3,2,4);
plot(freq,z_fft(1:length(freq)));
o=5;
wn=[1 10]*2/fs;
[b,a]=butter(o,wn,'bandpass');
figure;freqz(b,a,1000,fs);
hafis radzihttps://es.mathworks.com/matlabcentral/profile/authors/14191215-hafis-radzitag:es.mathworks.com,2005:Question/4160302018-08-23T21:22:34Z2019-03-24T07:19:29Zconvert multiple .txt into .mat in same folderI want to automatically convert multiple .txt files in a folder into .mat file in same folder . How can i do it programmatically?cloudy snowhttps://es.mathworks.com/matlabcentral/profile/authors/8341333-cloudy-snowtag:es.mathworks.com,2005:Question/4519612019-03-24T02:20:44Z2019-03-24T07:15:51ZI'm trying to create Random Music Player and could use help!TLDR: I stream music in my dorm room 24/7 and the stations I listen to loop every 19 hours and 41 minutes, and it gets old. So I want to make a random music player with matlab.
I am using the randi function to generate a random number so that it chooses one. Now, I need it to realize that is the name of a song, grab it, and then play it.
Here is the code I have so far! Any help would be greatly appreicated as I am a beginer. (I know that I only have 12 songs so far, this is just a proof of concept for now).
r = randi(12);
%use the random number generated to select a song (all named 1.m4a or
%12.m4a or whatever)
%plug the song into the folling code that plays the song
[a, Fs] = audioread('__________.m4a');
plot(a(:,1))
p = audioplayer(a,Fs);
play(p)
%repeat process. I will eventually turn this into a fucntion that can
%smartly choose between playing another song or letting us hear from a DJ
%in the Fallout Video games, but right now I just want to get the random
%generation perfected.
Ian Masonhttps://es.mathworks.com/matlabcentral/profile/authors/11931774-ian-masontag:es.mathworks.com,2005:Question/4519912019-03-24T06:45:54Z2019-03-24T07:14:12ZMatrix from linear equations I have very long equations and I want to convert them into matrix form by using the code below.
syms q1dd q2dd q3dd q4dd
oldVar = [diff(q1(t),t),diff(q2(t),t),diff(q3(t),t),diff(q4(t),t),...
diff(q1(t),t,t),diff(q2(t),t,t),diff(q3(t),t,t),diff(q4(t),t,t),...
q1(t), q2(t), q3(t), q4(t)]
newVar = [q1dot, q2dot, q3dot, q4dot,...
q1dd, q2dd, q3dd, q4dd,...
q_1, q_2,q_3, q_4]
Eq1 = subs(Eq1,oldVar,newVar)
Eq2 = subs(Eq2,oldVar,newVar)
Eq3 = subs(Eq3,oldVar,newVar)
Eq4 = subs(Eq4,oldVar,newVar)
Eqns = [Eq1 Eq2 Eq3 Eq4]
Vars = [q1dd q2dd q3dd q4dd]
[W, y]=equationsToMatrix([Eq1, Eq2, Eq3, Eq4],[q1dd, q2dd, q3dd, q4dd])
I am taking this error.
Error using sym.getEqnsVars>checkVariables
(line 83)
The second argument must be a vector of
symbolic variables.
Error in sym.getEqnsVars (line 53)
checkVariables(vars);
Error in sym/equationsToMatrix (line 55)
[eqns,vars] = sym.getEqnsVars(argv{:});
What could be the reason behind this error, I spent a couple of hours but I could not figure it out.
Thanks in advence!Görkem Günayhttps://es.mathworks.com/matlabcentral/profile/authors/12061568-gorkem-gunaytag:es.mathworks.com,2005:Question/4519842019-03-24T05:44:47Z2019-03-24T06:55:19ZExcel I/o matlabThe attached Distances.xlsx file contains a spreadsheet with the pairwise distances in miles of the top 100 US cities by population. A preview of the spreadsheet is shown below. The first row and first column contain the city names using the following format: city name comma space capitalized state abbreviation, e.g., Nashville, TN. Note that the very first cell of the spresheet, A1, is blank.
Write a function called get_distance that accepts two character vector inputs representing the names of two cities. The function returns the distance between them as an output argument called distance. For example, the call get_distance('Seattle, WA','Miami, FL') should return 3723. If one or both of the specified cities are not in the file, the function returns -1.
Preview of the first five cities of Distances.xlsx
Priyamvada Shankarhttps://es.mathworks.com/matlabcentral/profile/authors/15104143-priyamvada-shankartag:es.mathworks.com,2005:Question/4519852019-03-24T05:46:42Z2019-03-24T06:54:22ZUnexpected behaviour when calling main function with 2 outputsFor this function, I'm expecting 2 outputs when I run the script (n,p). However, I only get one 'n' when I run. Why?
function [n, p] = SandboxFile()
clear all
clc
n = 5;
p = 6;
end
Shivam Sahebhttps://es.mathworks.com/matlabcentral/profile/authors/9719829-shivam-sahebtag:es.mathworks.com,2005:Question/4519702019-03-24T03:42:18Z2019-03-24T06:12:10ZI have to concatenate 6 .mat eeg filesI have to concatenate six .mat files that contains EEG data. The data has 8 channels and different samples.
I want to concatenate the data column wise so that there are 8 rows for channels and the samples keep on adding column wise.Harshini Gangapuramhttps://es.mathworks.com/matlabcentral/profile/authors/13329200-harshini-gangapuramtag:es.mathworks.com,2005:Question/4519862019-03-24T05:49:18Z2019-03-24T06:10:48ZHelp with error using vpasolve! Im trying to graph Euler curves of Material Resistances using the secant formula.
Curves that should look like this:
But instead I have some (I believe in my inocence and inexperience) "errors" on some points of my formula that make the graph look like this:
So the first part is actually correct, but clearly those spikes are not, and Im having a hard time pinpointing the error, the code is really basic:
"La" being the horizontal axis, and "X" the vertical one/ "e" are each different curve which is excentricity./"Tcr" is maximum tension
for j=1:length(e)
for i=1:length(La)
S=0;
Tcr=(pi()^2*190000)/(La(i)^2);
syms x;
S=vpasolve(x*(1+e(j)*sec((La(i)/2)*sqrt(x/190000)))==Tcr,x);
R(i)=S;
end
plot(La,R,'-')
end
I believe so much so, is not an error in the mathematics, but probably the coding or the functions used that spiral in the error.
HELP! please! Thanks for your suggestions!dani serehttps://es.mathworks.com/matlabcentral/profile/authors/10483441-dani-seretag:es.mathworks.com,2005:Question/4519632019-03-24T02:33:02Z2019-03-24T06:05:45ZMy code isnt looping until answer is foundfunction [n] = NEWTON(x,err)
f1=@(x)(-9*x^5-8*x^3+12);
f2=@(x)(45*x^4-24*x^2);
%use equation
xnew = x - (f1(x)/f2(x));
%evaluate
if abs((xnew - x )/xnew) > err
xs = xnew;
else
x = xnew;
end
fprintf('The optimization estimate is=%f', xs);
end
I am trying to use newtons mathod to find the iptimization estimate, but it is only doing one iteration and then stopping, I am unsure how I can make it go until the answer is there within the error limit. Anthony Minghttps://es.mathworks.com/matlabcentral/profile/authors/14562039-anthony-mingtag:es.mathworks.com,2005:Question/4519872019-03-24T05:52:22Z2019-03-24T05:56:53Zmatlab simulink code generation error
We had created a inverse kinematic model of kinova robotic model in simulink and it was simulating without error. But when we tried to generate the code for the simulink mode we were getting the below error stating to modify the "joint.m" file. It is a system function of simulink model where we were not able to modify it. we had attached a screen shot where the sytem is asking to modify the joint.m file. Code generation is very crucial for our project. So please help us to solv the error.
Simulink detected an error 'Declaration of upper bound size as Inf is not supported. Please consider enabling dynamic memory allocation to allow unbounded sizes.'. The error occurred for MATLAB System block 'sairam_generated_kinovaa_ik/Inverse Kinematics/MATLAB System'. See line 149, column 13 in file 'C:\Program Files\MATLAB\R2018b\toolbox\robotics\robotmanip\+robotics\Joint.m'. The error was detected during code generation phase. Start code generation report. To prevent this error, modify the System object to avoid code that does not support code generation.Sriniketh Kondurihttps://es.mathworks.com/matlabcentral/profile/authors/15104329-sriniketh-konduritag:es.mathworks.com,2005:Question/4519812019-03-24T05:01:16Z2019-03-24T05:44:21Zhow access structure of array element using loop
Firstly i'm beginner in matlab,i don't have enough knowledge to write code in matlab.
Can i access Structure of array element using for loop?when i run this code,going to infinite loop i can't understand what's the problem.Please correction my code.
% Structure of Array of user set
user(1).will = 0.5;
user(1).rep = 1;
user(1).bid = 5;
user(1).inter_time=4;
user(2).will = 0.9;
user(2).rep = 0.6;
user(2).bid = 6;
user(2).inter_time=7;
% Structure of Arrayof task set
task(1).bud = 8;
task(1).qua = 1;
task(2).bud = 9;
task(2).qua = 2;
task(3).bud = 7;
task(3).qua = 1;
for i=1:2
for j=1:3
while(user(i).bid<=task(j).bud)
com_data_quality = (user(i).will*user(i).rep/user(i).bid*user(i).inter_time);
fprintf('%f value is\n', com_data_quality);
end
end
end
Sanjoy Deyhttps://es.mathworks.com/matlabcentral/profile/authors/15087902-sanjoy-deytag:es.mathworks.com,2005:Question/4518062019-03-22T22:05:00Z2019-03-24T05:42:44Zlooping image analysis problem.I've been attempting to have my code run a set of images, and they all have the same naming format, and I want to analyze them, but when I try to loop them, it keeps going on and on and on with no end. What am I doing wrong?
My code loop:
clear all;
image='img_000000000_Default_000.tif';
s=4;
results=zeros(2,s+1);
for i = 0:s
while (i<10)
image=['img-00000000', int2str(i), '_Default_000.tif'];
end
while (i<100 && i>= 10)
image=['img-0000000', int2str(i), '_Default_000.tif'];
end
while (i<1000 && i>=100)
image=['img-000000', int2str(i), '_Default_000.tif'];
end
results(1:2,i+1) = imagefunction(image,3);
end
My code for imagefunction
function [tubemean, tablemean] = imagefunction(image,boxsidelength)
imagex=imread(image);
imshow(image);
boxalter = (boxsidelength-1)/2;
newimage1= zeros(110-(2*boxalter), 130-(2*boxalter));
boxstartpointx = 370 + boxalter;
boxendpointx=480-boxalter;
boxstartpointy=150+boxalter;
boxendpointy=280-boxalter;
box1startpointx = 420 + boxalter;
box1endpointx=426-boxalter;
box1startpointy=201+boxalter;
box1endpointy=208-boxalter;
image1sum=0;
pixelcount1=0;
box2startpointx = 458;
box2endpointx=464;
box2startpointy=181;
box2endpointy=188;
image2sum=0;
pixelcount2=0;
for r = boxstartpointx:boxendpointx
for c = boxstartpointy:boxendpointy
box=imagex(r-boxalter:r+boxalter,c-boxalter:c+boxalter);
boxmean= mean2(box);
boxstd= std2(box);
eqn= boxstd/boxmean;
newimage1(r-(370-boxalter),c-(150-boxalter)) = eqn;
end
end
for r=box2startpointx:box2endpointx
for c = box2startpointy:box2endpointy
image2sum=image2sum+imagex(r,c);
pixelcount2=pixelcount2+1;
end
end
for r=box2startpointx:box2endpointx
for c = box2startpointy:box2endpointy
image2sum=image2sum+imagex(r,c);
pixelcount2=pixelcount2+1;
end
end
for r=box1startpointx:box1endpointx
for c = box1startpointy:box1endpointy
image1sum=image1sum+imagex(r,c);
pixelcount1=pixelcount1+1;
end
end
imagemean=mean2(image);
imshow(imagex);
tubemean=imagemean;
tablemean=image2sum/pixelcount2;
Images are .tif btw, if that is importantVidur Joshihttps://es.mathworks.com/matlabcentral/profile/authors/13219542-vidur-joshitag:es.mathworks.com,2005:Question/4519772019-03-24T04:07:32Z2019-03-24T05:41:58ZAdd echo to audio signal in matlabWrite a function called echo_gen that adds an echo effect to an audio recording. The function is to be called like this:
output = echo_gen(input, fs, delay, amp);
where input is a column vector with values between -1 and 1 representing a time series of digitized sound data. The input argument fs is the sampling rate. The sampling rate specifies how many samples we have in the data each second. For example, an audio CD uses 44,100 samples per second. The input argument delay represent the delay of the echo in seconds. That is, the echo should start after delay seconds have passed from the start of the audio signal. Finally, amp specifies the amplification of the echo which normally should be a value less than 1, since the echo is typically not as loud as the original signal.
The output of the function is a column vector containing the original sound with the echo superimposed. The output vector will be longer than the input vector if the delay is not zero (round to the nearest number of points needed to get the delay, as opposed to floor or ceil). A sound recording has values between -1 and 1, so if the echo causes some values to be outside of this range, you will need to normalize the entire vector, so that all values adhere to this requirement.
MATLAB has several sample audio files included that you can try: splat, gong, and handel are a few examples. Try the following:
load gong % loads two variables, y and Fs
sound(y, Fs) % Outputs sound Priyamvada Shankarhttps://es.mathworks.com/matlabcentral/profile/authors/15104143-priyamvada-shankartag:es.mathworks.com,2005:Question/3752112018-01-02T13:09:42Z2019-03-24T05:41:34Zcalculate frequency response from two signal on domain time in matlabHi,
I have arrays sample in time domain of input and output signal. size of vector is 2002 samples.
I want to find frequency response.
I wrote
[h,w] = freqz(y,x,2002);
figure()
plot(abs(h))
but I get very strange graph. I assume to see filter.
I want to calculate frequency response of smartphone(Audio filter)
What do I do wrong ?Alex Dashevskyhttps://es.mathworks.com/matlabcentral/profile/authors/10070405-alex-dashevskytag:es.mathworks.com,2005:Question/4519592019-03-24T01:54:44Z2019-03-24T05:39:45ZMatlab slows down after few iterationsI am running a matlab code for time evolving a system by von neumann equation, Euler method or Rk2, or Rk4.
Euler method is faster than the other two considering the matrix operations involved(but will have to use smaller steps and more runs).
If I make my matrix sparse the memory used is significantly less(since most of the elements are zero) and the code is faster in my PC(8 threads, i5 8th gen).
It seems that when computing using sparse matrix, matlab doesn't use parallel computing(I checked resource monitor), if I use full-matrix all cores are equally being used.
I kind of verified this by running it in a server with 64 cores and 1TB ram, Sparse calculations were running with similar speeds as my PC!, but operations with full matrix were lot better(but kind of still not as good as sparse calculations).
All those things I am evaluating in my iterations are pre allocated.
Spinz is a pre allocated vector, rhoT and H are matrix defined before, I can make these matrix sparse, to speed up.
for nt=1:Nt
Spinz(nt)=trace(rhoT*LSpinz)
rhoT = rhoT -(1i*dt*(H*rhoT - rhoT*H)/hbar);
end
My issue is if I run it for very long iterations(30000) the code is becoming slow, not like exponentially slow, but still.
Can anyone help me with ways to identify a method to make the program faster for such long iterations.
*sample H=diag(ones(1600,1),1);
*when sparse, H=sparse(H);Abhin Sureshhttps://es.mathworks.com/matlabcentral/profile/authors/15115924-abhin-sureshtag:es.mathworks.com,2005:Question/4519802019-03-24T04:57:25Z2019-03-24T05:39:22ZSeparating a vector into two different vectorsHello everyone, I need helping with sorting elements within a column vector. Let's say for example I had a column vector consisting of 100 elements but I wanted to separate them into two different vectors. The first vector would have every other 10 elements. So it would have the first 10 elements, skip the next 10, and then have the 10 after into it. The second vector I would want to make would contain every other element that was not sorted into the first one so elements 11-20 and so on. Would appreciate some guidance on where to start. Thank you in advance.
Lighthttps://es.mathworks.com/matlabcentral/profile/authors/7604900-lighttag:es.mathworks.com,2005:Question/4519482019-03-23T22:42:27Z2019-03-24T05:32:36ZHow can i create two subplotI am using a for loop which is giving me 16 plots. I want to put 8 in one subplot and the remaining 8 in the subplot 2. i am using the following code:
models{ct} = arx(ze1,[[na1_ na2_] [nb1_ nb2_] nk]);
if ct<10
figure(1)
s(1)=subplot(3,3,ct)
else
figure(2)
s(2)=subplot(3,3,ct)
end
unfortunately after putting 3 plots in subplot 1, matlab is giving me the following error:
"Error using subplot (line 327)
Index exceeds number of subplots"
how can i generate two subplots with 8 plot in each of them.
thanksMdRezwan Parvezhttps://es.mathworks.com/matlabcentral/profile/authors/7671110-mdrezwan-parveztag:es.mathworks.com,2005:Question/4519722019-03-24T03:48:50Z2019-03-24T05:31:26ZHow to perform STFT? NOT AN AUDIO FILEHow to perform STFT for EEG data?
All the examples have an audio file. But I dont have audio file and I have to perform STFT.
How to do that?Harshini Gangapuramhttps://es.mathworks.com/matlabcentral/profile/authors/13329200-harshini-gangapuramtag:es.mathworks.com,2005:Question/3606672017-10-10T20:42:19Z2019-03-24T05:31:00ZTest post for updatesTest post for updatestrehttps://es.mathworks.com/matlabcentral/profile/authors/9528791-tretag:es.mathworks.com,2005:Question/4519672019-03-24T03:27:15Z2019-03-24T05:28:52Z.mat files database hello everyone
I'm beginner at matlab database
i just want to ask , if i have .mat files for heartbeat how to make it in database ?
is there toolbox in matlab for this kind of project
or should i first convert it to sql and then link it with matlab as database ?
and what to query in heartbeat database ?
Rahaf mutlaqhttps://es.mathworks.com/matlabcentral/profile/authors/14458701-rahaf-mutlaqtag:es.mathworks.com,2005:Question/4519582019-03-24T01:42:01Z2019-03-24T05:26:12ZHow to mix two images in loop with 10%step. I want to mixed two pics in mat (A and B) with 10% step. It will create a 10 pics. It can be code like this. But I would like to write it down like loop, so it looks better.
clear all, close all
load('OBRAZKY/tvare.mat')
c=A
figure, imshow(c)
c1=0.9*A+0,1*B
figure, imshow(c1)
c2=0.8*A+0.2*B
figure, imshow(c2)
c3=0.7*A+0.3*B
figure, imshow(c3)
c4=0.6*A+0.4*B
figure, imshow(c4)
c5=0.5*A+0.5*B
figure, imshow(c5)
c6=0.4*A+0.6*B
figure, imshow(c6)
c7=0.3*A+0.7*B
figure, imshow(c7)
c8=0.2*A+0.8*B
figure, imshow(c8)
c9=0.1*A+0.9*B
figure, imshow(c9)Michaela Syrovatkovahttps://es.mathworks.com/matlabcentral/profile/authors/14859263-michaela-syrovatkovatag:es.mathworks.com,2005:Question/4519682019-03-24T03:28:55Z2019-03-24T05:19:38ZHow can I solve the nonlinear equations for X , Cs and Cc ?xguess = [4. 5.]; % initial guess vector
function fx = MNLEfun(x)
Cc = x(1);
Cs = x(2);
umax = 0.8;
Km = 4;
Csoo = 10;
Cso = 10;
Ysc = 2;
rg = umax * Cs * Cc / (Km + Cs);
rs = 0 - (Ysc * rg);
V = 5000;
vo = 1000;
D = vo / V;
Cco = 4.33;
X = 1 - (Cs / Csoo);
fx(1,1) = (D * Cs - rg );
fx(2,1) = (D * (Cso - Cs) + rs);
end
How can I solve the nonlinear equations for X , Cs and Cc ?
Thanks for the helpAli zainhttps://es.mathworks.com/matlabcentral/profile/authors/15115702-ali-zaintag:es.mathworks.com,2005:Question/4519732019-03-24T03:51:36Z2019-03-24T05:02:39ZHow can I access a cell array's data from another cell array?Hello. First of all, sorry if I'm not clear, english is not my native tongue... I have the next problem: I made a for loop to create X different inputdlg with 6 different boxes to complete in each one. Let's say X=3.So I ended up with a 3x1 cell array, and in each position ({1,1}, {2,1} and {3,1}) I have a 6x1 cell array as well. Now I have to convert the 6x1 cell array into ordinary arrays. I know there's a function called cell2mat to do this. But it only works if I indexed the three 6x1 cell arrays separately first.
Here's an example:
a = {{1;2;3;4;5;6};{7;8;9;10;11;12};{13;14;15;16;17;18}} % with x=3 and having already completing the 6 different boxes in my inputdlg text boxes
% if I write
b = a{1,1};
c = a{2,1};
d = a{3,1};
% and
e = cell2mat(b);
f = cell2mat(c);
g = cell2mat(d);
I have the ordinary arrays I want: e, f and g. And I can work with them now. But I don't know the value of X, it's assumed to change depending on different circumstances. So I need a for loop to get as many ordinary arrays as different values X con take. Is there a way to do this? Thank you very much!
Federico Manchinihttps://es.mathworks.com/matlabcentral/profile/authors/15116211-federico-manchinitag:es.mathworks.com,2005:Question/433262012-07-11T13:47:56Z2019-03-24T04:58:40ZCreate Figure Without Displaying itHi,
I'd like to create a figure and save it in the background without displaying it.
I've heard of setting the "visibility" setting to "off", but the figure window still pops up.
I'd rather just have the figure be created and saved in its specified folder without having to see it.
Any way to do this?
Thanks,
JFJohn Fhttps://es.mathworks.com/matlabcentral/profile/authors/2301285-john-ftag:es.mathworks.com,2005:Question/4519762019-03-24T04:05:25Z2019-03-24T04:56:37ZUndefined function or variable 'equationsToMatrix'.Hi all,
I encountered an issue when I tried to solve the systematic equations.
By following the instructions from https://www.mathworks.com/help/symbolic/equationstomatrix.html, I typed in the exact same codes in to Matlab:
syms x y z
eqns = [x+y-2*z == 0,
x+y+z == 1,
2*y-z == -5];
[A,b] = equationsToMatrix(eqns)
However, I got the error:
Undefined function or variable 'equationsToMatrix'.
I did some search and could not find any solutions. Plus, my MaLab software is installed under the C:/ directory.
Any help would be higly appreciated!
Thanks,
-YiliYili Zhanghttps://es.mathworks.com/matlabcentral/profile/authors/13450165-yili-zhangtag:es.mathworks.com,2005:Question/4519782019-03-24T04:08:17Z2019-03-24T04:47:31Zhow can I determine amplitude, phase and frequecy in FFT?The signal I have attached like this. If I give the L value is equal to length of time, the value is 1501. But frequency matrix is coming 1 by 751. So for this plotting issue is coming. Phase part i am unable to do.
So, what will be the correct code for frequeency, amplitude and phase?
I have tried to do it with this code
Time= 0:2:3000;
tt=time;
ss=signal;
Ts = mean(diff(tt)); % sampling time
Fs=500; %sampling frequency
Fn=Fs/2;
L=length(tt);
Y=fft(ss);
P_amp=abs(Y/L);
f=Fs*(0:(L/2))/L;Amrita Singhhttps://es.mathworks.com/matlabcentral/profile/authors/4585840-amrita-singhtag:es.mathworks.com,2005:Question/4490532019-03-08T17:09:11Z2019-03-24T04:37:09Zhow divide image to blocks?I want to divided image to non-overlapping blocks, then I will appliy DWT on each block
can any one help me with this pleaseMohammed Kassemhttps://es.mathworks.com/matlabcentral/profile/authors/14083214-mohammed-kassemtag:es.mathworks.com,2005:Question/780092013-06-04T20:17:09Z2019-03-24T04:35:54ZCreate an image stack (3-D matrix)Hello. I'm importing a series of images from my working directory using the following code:
for i=139:141
% {} = cell array
images{i} = imread(sprintf('IMG_%04d.JPG',i));
I{i} = rgb2gray(images{i});
end
I have a large number of images, but here I'm importing just a sample. I'm converting each color image to grayscale. I must also create an image stack, a 3D matrix of grayscale images. I've been browsing the web for an answer, but I'm having difficulty understanding the process. size(I) yields '1 141', and I'm wondering how I can create a 3-D matrix from this. Your help would be greatly appreciated. Thank you!Jackhttps://es.mathworks.com/matlabcentral/profile/authors/4281808-jack