How can I create a matrix or cell array for a changing condition?

조회 수: 11 (최근 30일)
Ben Mound
Ben Mound 2020년 3월 27일
댓글: Ben Mound 2020년 3월 28일
Hi,
I have an irregularly spaced time vector and I would like to create a matrix or cell array with the first column holding all values between 0-6 seconds and the 2nd column 6-12 etc. Im pretty sure there is an easy solution but I am new to matlab and cant find one.
Below is the code I have so far, the result is a matirx which seems to do most of what Im asking but only displaying the first value for each condition.
Any help would be greatly appreciated.
Ben
Cycles = 2
% Vector with irregularly spaced time values
sig_time = [0 0.21 1.83 2.91 2.93 4.04 5.38 5.65 6.89 7.22 7.54 8.62 9.11 9.87 10.02 10.56 11.88 12]'
% Creating Empty Sigma Matrix
Sig_Vec=NaN(length(sig_time),Cycles);
Period = 0;
i=1;
% Seperating Sigma By Cycles
for ii = 1:length(sig_time)
if (Period<=sig_time(ii) && sig_time(ii)<=Period+6)
Sig_Vec(ii,i)=(sig_time(ii));
Period=Period+6;
i=i+1;
end
end
% Result
0 NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN 6.89
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN
NaN NaN

채택된 답변

Tommy
Tommy 2020년 3월 28일
편집: Tommy 2020년 3월 28일
Rather than looping through each value in sig_time, loop through the cycles (i.e. array columns):
Period = 0;
for i = 1:Cycles
subset = sig_time(Period <= sig_time & sig_time < Period+6); % all values in sig_time between Period and Period+6
Sig_Vec(1:length(subset),i) = subset;
Period = Period+6;
end
You may prefer to go with the cell array so you don't have to deal with the NaN values:
Sig_Vec = cell(1,Cycles);
Period = 0;
for i = 1:Cycles
Sig_Vec{i} = sig_time(Period <= sig_time & sig_time < Period+6);
Period = Period+6;
end
but of course that means you have to deal with cells.
  댓글 수: 1
Ben Mound
Ben Mound 2020년 3월 28일
Hi Tommy,
Really appreciate the reply, that worked perfectly and saved me a lot of agro! Thank you very much.
Kind reagards,
Ben

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by