Venkat kamal
Venkat kamal

Reputation: 279

Adding elements in a column based on unique elements of another column

I have a matrix called as single_matrix_with_time_id, the first column corresponding to frame_number, second column corresponding to time, third column with identity, fourth column with error, fifth and sixth column with X and Y coordinates and seventh column with Camera_id.

What i am trying to do is to take the unique elements from the second column (time) and the elements corresponding to the unique elements of time from the first and seventh column and add it to first, second and third column of a new matrix called final_plot_matrix. I tried to do this in the code shown below, But it is not giving me the expected outcome. Code and image of the single_matrix_with_time_id is attached. Any help will be appreciated.

final_plot_matrix = nan(length(unique(single_matrix_with_time_id(:,2)))+1,length(final_filtered_ant_id)+3);
final_plot_matrix(1,4:length(final_filtered_ant_id)+3) = 
final_filtered_ant_id;
final_plot_matrix = repelem(final_plot_matrix,1,2);
final_plot_matrix(:,1) = [];
final_plot_matrix(:,2) = [];
final_plot_matrix(:,3) = [];
final_plot_matrix(2:length(unique(single_matrix_with_time_id(:,2)))+1,3) = unique(single_matrix_with_time_id(:,2));
[C,ia,ic] = unique(single_matrix_with_time_id(:,2));
frame_number = ia(single_matrix_with_time_id(:,1));
Camera_id = ia(single_matrix_with_time_id(:,3))
final_plot_matrix(2:length(unique(single_matrix_with_time_id(:,2)))+1,2) = frame_number
final_plot_matrix(2:length(unique(single_matrix_with_time_id(:,2)))+1,1) = Camera_id

single_matrix_witj_time_id

Upvotes: 0

Views: 59

Answers (1)

Mike Scannell
Mike Scannell

Reputation: 378

It looks like you were on the right track using "unique", but it should be more simple than that. Call unique on the time data (second column) to get the unique row numbers. Unique returns unique values as the first output, and the indices as the second. We only care about the indices, so ignore the first output.

[~, ia] = unique(single_matrix_with_time_id(:,2);

Now you know the row and column numbers you want from the original data. Row numbers are in "ia", and you want columns 1, 2, and 7. So make a new matrix:

final_plot_matrix = single_matrix_with_time_id(ia,[1 2 7]);

That's it! If you wanted to switch the order of the columns (for example, to make time the first column instead of second), just switch the order of the columns in the line above. For example:

final_plot_matrix = single_matrix_with_time_id(ia,[2 1 7]);

Upvotes: 1

Related Questions