Adding numbers in one column and move the values in second column accordingly?
7 views (last 30 days)
Show older comments
Hi,
I have a n*2 array. Say Array 1: [0,4,5,6...n], Array 2: [0.1,0.2,0.3,0.4....n]. I want to make Array 1 as [0,1,2,3,4,5,6....n]. I also want the elments in Array 2 shift accordingly. For the new values of Array 1, array two should be blank. I will appreciate quick resposne.
0 Comments
Answers (2)
Sindar
on 23 Jan 2020
Edited: Sindar
on 23 Jan 2020
% set up examples:
a1 = [0,4,5,6,7];
a2 = [0.1,0.2,0.3,0.4,0.5];
a1_new = [0:7];
% find locations of a1 in a1_new
[~,loc]=ismember(a1,a1_new);
% prepare a2_new as "empty" (full of NaN's)
a2_new=nan(size(a1_new));
% fill in appropriate elements
a2_new(loc)=a2;
3 Comments
Sindar
on 23 Jan 2020
So combine the versions above and swap rows->columns:
% set up example:
a1 = [0,4,6,8,9,10];
a2 = [0.1,0.2,0.3,0.4,0.5,0.6];
a3 = [0,1,2,3,4,5,6,7,8,9,10];
% find locations of a1 in a3
[~,loc]=ismember(a1,a3);
% prepare a_new
% first column is transpose of a3
% second column is same size, starting with all elements "empty" (full of NaN's)
a_new = [a3' nan(size(a3'))];
% fill in appropriate elements of 2nd column from a2
a_new(loc,2)=a2;
BTW, the only way to have "blank" values in a numeric away is to set them to NaN.
See Also
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!