if difference between two values is smaller than replace by

I have a vector that contains several time values. For the application I need to check if the difference between two values is smaller than 3e-6. If that's the case the second (higher) value shall be replaced with the first.
My approach would be for-loops but maybe there is a smarter and more efficient way to solve this?

댓글 수: 5

Dyuman Joshi
Dyuman Joshi 2023년 10월 22일
편집: Dyuman Joshi 2023년 10월 22일
Are you taking the values adjacently/consecutively? or 1/2/.../n after the other? or randomly?
Can you upload the data (or a small, representative sample)? You can use the paper clip icon in the INSERT section of the toolbar.
(There are several ways to store time values in MATLAB, and the syntax will be different depending on the data type.)
Kai
Kai 2023년 10월 22일
이동: the cyclist 2023년 10월 22일
I attached you the data. This are the switching times for 6 MOSFETs.
I need to supplement, that in case the difference between two values is zero, no action needs to be taken.
Is each column processed independently?
As @Dyuman Joshi asked, do you only need to check consecutives values?
It doesn't seem that any value is greater than the immediately preceding value by less than 3.e-6, but more than zero:
load("time.mat","time")
any((diff(time) > 0) & (diff(time) < 3.e-6),"all")
ans = logical
0
load("time.mat","time")
dt = diff(time);
dt = dt(dt ~= 0);
min(dt)
ans = 1.3500e-05
So in all cases where the difference in times is < 3e-6, the two values are already identical.

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

 채택된 답변

Pratyush
Pratyush 2023년 10월 23일
Hi Kai,
I understand that you have a vector, and if the difference between any two values is less than 3e-6, you want to set them both equal to the lesser of the two numbers. The following script could be used for that purpose:
% Sort timeValues vector
timeValues = sort(timeValues);
% Calculate the differences between adjacent values
diffValues = diff(timeValues);
% Find the indices where the differences are smaller than 3e-6
replaceIndices = find(diffValues < 3e-6);
% Replace the second value with the first for the identified indices
timeValues(replaceIndices + 1) = timeValues(replaceIndices);
Hope this helps.

댓글 수: 1

Note that this answer sorts the data before finding difference between consecutive elements.
OP has/had not specified anything in regards to that.

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Get Started with MATLAB에 대해 자세히 알아보기

제품

릴리스

R2021a

질문:

Kai
2023년 10월 22일

댓글:

2023년 10월 23일

Community Treasure Hunt

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

Start Hunting!

Translated by