How do get loop results into a vector or matrix in matlab - 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

Related

Create an array that grows at a regular interval on Matlab

I have been thinking about how to create an array that grows at a regular interval of time (for instance every 5 seconds) on Matlab.
I figured out 2 ways, either using tic/ toc or timer function. Later this program will be complexified. I am not sure which way is the best but so far I am trying with using timer.
Here is what I have tried :
clc;
period=5;%period at which the file should be updated
freq=4;
l=freq*period;
time=[0];
a = timer('ExecutionMode','fixedRate','Period',period,'TimerFcn',{#time_append, time,l,freq},'TasksToExecute',3 );
start(a);
function [time]=time_append(obj,event,time,l,freq)
time_append=zeros(l,1);
last_time=time(end)
for i=1:1:l
time_append(i)=last_time+i/freq;
end
time=[time;time_append];
end
After compiling this code, I only get a time array of length 1 containing the value 0 wheras it should contain values from 0 to 3x5 =15 I think it is a stupid mistake but I can't see why. I have tried the debug mode and it seems that at the end of the line time=[time;time_append], the concatenation works but the time array is reinitialised when we go out of the function. Also I have read that callback function can't have output. Does someone would know how I could proceed? Using globals? Any other suggestion?
Thank you for reading
You can do this by using nested functions. Nested functions allow you to access "uplevel variables", and you can modify those. Here's one way to do it:
function [a, fcn] = buildTimer()
period=5;%period at which the file should be updated
freq=4;
l=freq*period;
time=0;
function time_append(~,~,l,freq)
time_append=zeros(l,1);
last_time=time(end);
for i=1:1:l
time_append(i)=last_time+i/freq;
end
time=[time;time_append];
end
function out = time_get()
out = time;
end
fcn = #time_get;
a = timer('ExecutionMode','fixedRate',...
'Period',period,...
'TimerFcn',{#time_append,l,freq},...
'TasksToExecute',3 );
start(a);
end
Note that the variable time is shared by time_append and time_get. The timer object invokes time_append, and updates time. You need to hand out the function handle time_get to retrieve the current value of time.
>> [a,fcn] = buildTimer; size(fcn()), pause(10); size(fcn())
ans =
21 1
ans =
61 1

convert cell to empty nested structure

imagine you have a cell Array "test" with two dimensions "e" and "f" of different size. Is it possible to convert this with one dimension to a struct while the other one to the substruct? It works with a Loop, but i don't like Loops. Cause the struct is empty before i can't arrange in an Array with [...].
StrA.SubA.SubSubA=struct('SubSubSubA',[],'SubSubSubB',[]);
count_e=4;
count_f=2;
for e=1:count_e
for f=1:count_f
StrA.SubA(e,1).SubSubA(f,1).SubSubSubA=test{e,f};
end
end
Thanks in advance
You can do this without loops using struct, num2cell, and a couple of transposes:
test = num2cell(rand(4, 2)); % Sample 4-by-2 cell array of random data
StrA = struct('SubA', struct('SubSubA', num2cell(struct('SubSubSubA', test, ...
'SubSubSubB', []).', 1)).');
Although I don't know if it will be any faster or more readable than the loop-based solution.
I should also note that in your loop-based solution, only substructures StrA.SubA(1).SubSubA(1) and StrA.SubA(1).SubSubA(2) will have a SubSubSubB field. All other substructures in StrA.SubA(2:4) will only contain the field SubSubSubA.

use structure in matlab

I want to use structure in matlab but in first iteration it's run correctly and in other iteration give that message .
1x2 struct array with fields:
my code is :
for i=1:lenfd
currow=rees(i,:)
maxcn=max(currow)
if maxcn~=0
maxin=find(currow==maxcn)
ress(i).x =maxin
end
end
thank you.
That message is not a warning or error. That's just MATLAB printing the output of an operation. And it does that by default, unless you suppress it by appending a semicolon to the command:
for ii = 1:lenfd
currow = rees(ii,:); % <=== NOTE: semicolons at the end
maxcn = max(currow);
if maxcn ~= 0
ress(ii).x = find(currow==maxcn);
end
end
Note that max() may have 2 outputs, the second output being the first index into the array where the maximum occurred. If you know beforehand that any maximum will occur only once, you can skip the call to find() and use the second output of max().

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.

Nested if statement in for loop

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.