Nested if statement in for loop - matlab

So heres my script
function printPower
sum=0;
filename=input('Enter a filename: ','s');
power=load(filename);
for i=1:length(power);
if power(i)>=0;
sum=sum+power(i);
end
TP=sum/24;
end
fprintf('Total power: %.1f kWh.\n', TP);
There are negative values in the text file im loading and I want it to only sum the positive ones but it still sums all values.

You could just replace your loop with something like
total = sum(power(power>=0))/24
Personally I think that using the name of a Matlab intrinsic function, such as sum, as a variable name is just asking for trouble though I'm not sure it's caused a problem in your case. That's why the lhs of my statement is the variable total.

Related

How to save and pass a variable in Matlab

I can find / identify all digits in a number using a recursive function.
My issue is trying to sum the number through each recursion.
I had to initialize sum = 0 at the top of my function statement, and when I return through recursion, I'm always resetting sum back to zero. I do not know how to save a variable without first initalizing it.
Code is below;
function output= digit_sum(input)
sum=0
if input < 10
output = input
else
y=rem(input,10);
sum=sum+y
z=floor(input/10);
digit_sum(z)
end
output=sum
end

Designing Function to Reduce Return Variables in Matlab

This is NOT a question where I need to know how to add A+B in MATLAB. This is more of a code design question.
I have few function files that return a numeric matrix and index info on the matrix. For example
function [Mat1, IdxID, IdxDate, IdxVal, IdxMarker, IdxOpen, ...] = First ()
....
.... % where IdxId = 1 ; IdxDate = 2 ; ...
end
function [Mat1, IdxUid, IdxName, IdxVal, Mat2, IdxUid2, IdxSalary2, ...] = Second ()
....
.... % where IdxUid= 1 ; IdxName= 2 ; ...
end
As you can see the code becomes clunky and when I call these functions, I have to declare an equal number of outputs to catch all the indices. The advantage is if I suddenly swap ID & Date columns, the calling functions do not change as I simply make ID=2, Date=1. I also have the advantage of renaming these variables inside the function.
Is there a better way to do this? I'm testing whether struct or cell can be used for indices. I can't use datasets or cell for returning numeric matrix. Too much time is lost in translating it into numbers. Thanks.
Yes, you can return arrays/cells/structs instead. For instance, id can be a struct with multiple variables. Your function definition could be as follows.
function [Mat, Id] = Second ()
...
end
In your function, have the following set:
Id.Name
Id.Val
Id.Salary
...
If you find that you have multiple structs with the same exact structure, you can even consider objects.
Please clarify with more details on the structure if you want a more detailed answer.

How can I plot these variables in Matlab?

I want to plot my variables for teta=0:360 degree. But I cant solve matrix problems. Plot all variables such as vc, ac, bzegon ,bdot.
teta=0:.1:2*pi;
w=2000*2*pi/60;l1=.05;l2=0.15;
beta=asin(l1/l2*sin(teta));
bdot=l1/l2*w*(cos(teta)./sin(beta));
xc=l1*cos.(teta)+l2*cos.(beta);
vc=-l1*w*sin.(teta)-l2*bdot.*sin.(beta);
bzegon=-l*w*(w*sin.(teta)*(xc-l1*cos.(teta))+cos.(teta)*(vc+l1*sin.(teta)))/((xc-l*cos. (teta))^2);
ac=-l1*w*cos.(teta)-l2*bzegon.*sin.(beta)-l2*bdot.*cos.(beta);
plot(teta,bdot);
set(gca,'XTick',0:pi/2:2*pi)
set(gca,'XTickLabel',{'0','pi/2','pi','3pi/2','2p'})
%title('bdot');
ylabel('bdot');
xlabel('radian');
replace:
xc=l1*cos.(teta)+l2*cos.(beta);
vc=-l1*w*sin.(teta)-l2*bdot.*sin.(beta);
bzegon=-l*w*(w*sin.(teta)*(xc-l1*cos.(teta))+cos.(teta)*(vc+l1*sin.(teta)))/((xc-l*cos. (teta))^2);
ac=-l1*w*cos.(teta)-l2*bzegon.*sin.(beta)-l2*bdot.*cos.(beta);
with:
xc=l1*cos(teta)+l2*cos(beta);
vc=-l1*w.*sin(teta)-l2*bdot.*sin(beta);
bzegon=-l1*w.*(w.*sin(teta).*(xc-l1*cos(teta))+cos(teta).*(vc+l1*sin(teta)))/((xc-l1*cos(teta)).^2);
ac=-l1*w.*cos(teta)-l2*bzegon.*sin(beta)-l2*bdot.*cos(beta);
You have to check all the parameters once again, maybe I messed up somewhere.
There are a lot of mistakes in your code with the . operator. You can't do cos.(beta), the . operator for element-by-element operation needs to be before things like multiply, add, subtract, raise to the power n, etc... Here's a corrected version of your code (I have assumed a scalar value for l which is not specified in your question):
teta=0:.1:2*pi;
w=2000*2*pi/60;l1=.05;l2=0.15;
l=l1+l2; % or whatever value, I assumed l was a scalar
beta=asin(l1/l2*sin(teta));
bdot=l1/l2*w*(cos(teta)./sin(beta));
xc=l1*cos(teta)+l2*cos(beta);
vc=-l1*w*sin(teta)-l2*bdot.*sin(beta);
bzegon=-l*w.*(w.*sin(teta).*(xc-l1*cos(teta))+cos(teta).*(vc+l1*sin(teta)))/((xc-l*cos(teta)).^2);
ac=-l1*w.*cos(teta)-l2*bzegon.*sin(beta)-l2*bdot.*cos(beta);
plot(teta,bdot);
set(gca,'XTick',0:pi/2:2*pi)
set(gca,'XTickLabel',{'0','pi/2','pi','3pi/2','2p'})
%title('bdot');
ylabel('bdot');
xlabel('radian');

how to compare values of an array with a single value in matlab

Can anyone tell me how to compare this for loop array value pp1 with the single value of pp. If the value of pp is present in pp1 then it must show 1 or must show 0. I'm getting 1 only the last value of pp1. The code is:
[pp,pf1]=pitchauto(x,fs);
for ix=1:2
V='.wav';
ie=num2str(ix);
Stc=strcat(ie,V);
[x1,fs1]=wavread(Stc);
figure,plot(x1);
title('Test Audio');
[pp1,pf1]=pitchauto(x1,fs1);
end
if (pp==pp1)
msgbox('Matching');
else
msgbox('Not Matching');
end
Kindly do reply with the correct answers.
You calculate a value for pp1 each time, do nothing with it, then let the next loop iteration overwrite it. To make use of it, either put the test inside the loop:
for ix=1:2
V='.wav';
ie=num2str(ix);
Stc=strcat(ie,V);
[x1,fs1]=wavread(Stc);
figure,plot(x1);
title('Test Audio');
[pp1,pf1]=pitchauto(x1,fs1);
if (pp==pp1)
msgbox('Matching', num2str(ix)); % show the index number as msgbox title
else
msgbox('Not Matching', num2str(ix));
end
end
or collect the values of pp1 in an array to test afterwards:
for ix=1:2
V='.wav';
ie=num2str(ix);
Stc=strcat(ie,V);
[x1,fs1]=wavread(Stc);
figure,plot(x1);
title('Test Audio');
[pp1(ix),pf1]=pitchauto(x1,fs1); % assuming pitchauto returns a scalar
end
matchidx = (pp == pp1);
if any(matchidx)
msgbox(strcat('Matching indices: ', num2str(find(matchidx))));
else
msgbox('Not Matching');
end
If the values aren't scalar, then this approach is a bit more difficult - you could still use a matrix to collect equal-sized vectors, or a cell array to collect anything - but it's probably easier to stick with the first approach in that case.

How do get loop results into a vector or matrix in matlab

Here is the thing:
I have while loop nested in a for loop.
I can get the results of each iteration as a result for the variable flp. But now i want all these results stored in a vector with same number of rows as another variable called eci. I'm aware that i have to preallocate the vector. But how do i move on from here?
Tank you!
Here is the code i've done so far:
for eci=0:0.0002:ecu
fl=0;
fcc=fc0*(2.254*sqrt(1+7.94*fl/fc0)-2*fl/fc0-1.254);
ecc=ec0*(1+5*(fcc/fc0-1));
r=Ec/(Ec-fcc/ecc);
x=eci/ecc;
fc=fcc*x*r/(r-1+x^r);
el=(Ec*eci-fc)/(2*beta*fc);
flp=ke*kr*2*nf*tf*Ef*1000*el/B;
while abs(fl-flp)>0.0001
fl=flp;
fcc=fc0*(2.254*sqrt(1+7.94*fl/fc0)-2*fl/fc0-1.254);
ecc=ec0*(1+5*(fcc/fc0-1));
r=Ec/(Ec-fcc/ecc);
x=eci/ecc;
fc=fcc*x*r/(r-1+x^r);
el=(Ec*eci-fc)/(2*beta*fc);
flp=ke*kr*2*nf*tf*Ef*1000*el/B
end
end
eci=[0:0.0002:ecu]';
m=size(eci);
m(:,2)=[];
mat_result=zeros(m,1)
Its quite stimple, start with an empty vector, for example:
results = zeros(length(0:0.0002:ecu),1);
Then just start counting with t=t+1 somewhere in the loop (initialize properly ofcourse) and store the restult:
results(t) = myResult