How do I make matlab read certain lines and do calculations only when a condition is true?
2 次查看(过去 30 天)
显示 更早的评论
Please see attached file. variables t and v represent time and velocity respectively. Z being the condition. I want to calculate average acceleration over the points where the condition is '1', and not when the condition is '0'.
I also want the calculation to be specific to the '1' sections. In other words, calculate the average acceleration for the first section where z is 1, and make that a vector value. Then calculate a separate average acceleration for the second section where z is '1', and so on for the rest of the data.
clear;
clc;
%----------------------------------------------------
uiimport %importing said csv file
while (1) %keeps code from running while selecting a file
cont=input('Press 1 then enter to continue:','s');
if cont=='1'
break
end
end
wrdvec = size(t);
a = repmat('1',[wrdvec,1]);
b = int2str(z)
abc = a==b
av = v(2:end,:) - v(1:end-1,:)
at = t(2:end,:) - t(1:end-1,:)
av = av./at;
avv = zeros(20,1);
for f = find(abc)
avv(f) = av
end
6 个评论
Bob Thompson
2018-2-26
Does avv need to be 20x1? You could just initiate the size of avv to be based on f. Additionally, there still needs to be agreement between av and f. Even if you have two arrays if you have one that's 18x1 and one that is 16x2 then Matlab is not going to want to join them.
采纳的回答
Abraham Boayue
2018-3-2
clear variables
% Test the loop with these values of t, v and z, it should work just fine
% for any data.
t = 1:10;
v = [ 3 4 5 7 3 2 8 2 1 6];
M = length(t);
z = [1 1 0 1 1 0 1 0 1 1];
A = [];
for k = 1:M
if(z(k)== 1)
a = v(k)/t(k);
A = [A; k a];
fprintf('A section (eg. 1 and 2) occurs after a number skip :counter of 1s before a 0 = %12.8f, a = %12.8f\n', k, a);
end
continue
end
%disp(A);
1 个评论
Abraham Boayue
2018-3-2
Hey Dylan, here I am with another simple code again. This time, I am positive that it does the job. See the output of the print statement. You did mention that you wanted a vector of the average acceleration for each section of ones, however, it is the value of z that decides whether you will get a vector or scalar. Eg. Z = [1 1 0 1 1 0 1] will give two vectors and a scalar.
更多回答(1 个)
Abraham Boayue
2018-2-26
编辑:James Tursa
2018-2-26
t = 0.1:0.1:2.1;
v= 1:21;
z = [ones(1,8) 0 ones(1,6) 0 0 ones(1,4)];
N=length (t)
a = zeros(1,N);
A1 = [];
A2 = [];
A3 = [];
for i =1:N
if(z==1 && v <=8) % condition
% for the
% 1st sect.
a(i) = v(i)/t(i);
A1 = [A1 a];
elseif ( z==1 ||v <=15)
a(i) = v(i)/t(i);
A2 = [V2 a];
elseif (z==1)
a(i)= v(i)/a(i);
A3 = [A3 a];
end
end
dis (' a for the first section ')
disp(A1)
disp('a for the second section )
disp(A2)
disp(' and a for the last section)
disp(A3)
4 个评论
Abraham Boayue
2018-2-26
Yes, I do have an idea. I just to have access to pc at this point, I will look into that when I do.
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!