Indexing changing values in a table
20 次查看（过去 30 天）
I have some data that I am collecting from some equipment. The data include x, y, and z values. x and y refer to the position and the z values are heights of the surface in micro meters. First three columns are x, y, and z. Last 3 columns are RGB codes (can be ignored now)
The data is attached. The y values change at constant intervals, and if you go to row 1860 you will notice that the y value changes. It will change at that same interval e.g. 1860, 3720. I am trying to write code that identifies at which row the y value changes. It will change multiple times in the data, and I want to identify at each point where it changes by telling the user "The y values are changing at 1860, 3720, etc".
The reason I need this to be flexible is that this piece of code should handle any data thrown at it (obviously in a similar format). So whether the y values change at 1860, 2000, 5, or whatever number, the user is informed of the positions.
I have tried using the code below:
filename = uigetfile("*.txt");
data = readtable(filename,"VariableNamingRule","preserve");
x_data = table2array(data(:,"Var1"));
y_data = table2array(data(:,"Var2"));
z_data = table2array(data(:,"Var3"));
numRows = size(y_data,1);
diffA = gradient(y_data);
Rows2Idx = zeros(length(y_data),1);
%Rows2Idx = any(diffA);
for i = 1:numRows
% if diffA ~= 0 % > 0 || diffA < 0
% Rows2Idx(k,1) = i;
while diffA(1:numRows,:) ~= 0
Rows2Idx(k,1) = i;
As you can see, I tried an If statement and while loop, I've tried a lot of other different things but I would say I'm officially stuck now. Any help would be appreciated. I've also tried using the diff function to identify when the difference between points is not equal to zero, and use that to index, but I am struggling.
Apologies if this is a bit confusing, happy to answer any questions.
Govind KM 2023-6-9
You can use the following code which uses the diff and find functions to return all indices where the y_data value is changing. You can then display each index of the result or perform further work as required.
%The actual indices at which the y_data values change will be
In the IF block that you have commented out, just change diffA to diffA(i,1) and you'll get the output.
Also, you can add another condition in the IF statement to not consider both the adjacent values where diffA is not zero.
for i = 1:numRows-1
if diffA(i,1) ~= 0 && diffA(i+1,1) ~= diffA(i,1)
Rows2Idx(k,1) = i;
This will store the correct indices in Rows2Idx but it will throw an error at the last line becasue of msgbox function. Refer to the doucmentation to fix that: https://in.mathworks.com/help/matlab/ref/msgbox.html