Info

이 질문은 마감되었습니다. 편집하거나 답변을 올리려면 질문을 다시 여십시오.

Vector manipulation for randomized data

조회 수: 3 (최근 30일)
Elijah L
Elijah L 2020년 11월 2일
마감: MATLAB Answer Bot 2021년 8월 20일
I have generated a vector "SleepData" that creates a 7200x1 vector of random #s from 0-12. I want the vector sensor data to have the value 1 when SleepData > 4. I have been able to do this.
I need help to make it so that the value of 1 lasts for 300 more indicies following the each initiation of 1. How can I do this?
% When sleep data >= 4cm , Have SENSOR = 1 (ON)
% If no data >=4cm for 300s, Have SENSOR = 0 (OFF)
% Display on plot when SENSOR is on or off and it's duration
SENSOR = zeros(length(SleepData),1);
SENSOR(SleepData>=4) = 1;
  댓글 수: 2
S. Walter
S. Walter 2020년 11월 2일
I am confused - you are creating a random vector with integers from 0 to 12 but then if the value is more than 4 you want to automatically make the following 300 entries equal to 1?
%% Housekeeping
clearvars
clc
close all
% Make a random vector
SleepData = randi(12,[7200,1]);
% Make a vector of 0's
SENSOR = zeros(size(SleepData));
% When SleepData is equal to or greater than 4, set it to 1
SENSOR(SleepData>=4) = 1;
% NEW CODE
% Find where the first instance is where the sleep sensor is triggered
I = find(SENSOR==1);
% For the next 300 instances, keep the sleep sensor on
SENSOR(I(1):I(1)+300)=1;
% Just for plotting
% Get the indices where the sensor is on
ON_idx = SENSOR==1;
% Make an iteration index
i = 1 : 1 : 7200;
% Plot where the sensor is off as a blue square
plot(i(~ON_idx),SENSOR(~ON_idx),'s')
hold on
% Plot where the sensor is on as a red circle
plot(i(ON_idx),SENSOR(ON_idx),'o')
Elijah L
Elijah L 2020년 11월 2일
This works but only for the first initiation of the value 1. Everytime that SENSOR =1, I want it to "hold" the value for 300 intances. How would I do this?

답변 (1개)

Sourabh Kondapaka
Sourabh Kondapaka 2020년 11월 6일
편집: Sourabh Kondapaka 2020년 11월 6일
You are right in suggesting S. Walter's code would only update for the first occurance of 1. In the below code, I added a for-loop which will do the desired operation for all the occurances of 1's. Only the occurances of 1's before performing the desired operation(making the next 300 index values 1's) will be considered.
clearvars
clc
close all
% Make a random vector
SleepData = randi(12,[7200,1]);
% Make a vector of 0's
SENSOR = zeros(size(SleepData));
% When SleepData is equal to or greater than 4, set it to 1
SENSOR(SleepData>=4) = 1;
% Get all indices where SENSOR value is 1.
indices = find(SENSOR==1);
% This for loop will iterate over the occurance of 1s which occured before performing the
% desired operation(making the next 300 index values 1)
%Iterate over each of the occurance and make the next 300 index values 1
for i = 1:length(indices)
SENSOR(indices(i): indices(i)+300) = 1;
end

태그

Community Treasure Hunt

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

Start Hunting!

Translated by