Adding numbers in one column and move the values in second column accordingly?

7 views (last 30 days)
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.

Answers (2)

Sindar
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
Khizar Rouf
Khizar Rouf on 23 Jan 2020
Hi Sindar,
Thanks for providing the codes, but they are not working for my case. I may not have make clear what I am looking for. I am going to explain again. I hope it would be clear now.
I have three columns (not rows) as follows:
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]
I want to make a new array (n*2 (rows*column)) such that it has all elements of a3 in the first column. In the second column, it should have only corresponding values which will come from a2. If there is no value present, then a2 should remain blank for that particular value. For example, there will be a value for 0 but not for 1,2,3. Thanks
Sindar
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.

Sign in to comment.


Khizar Rouf
Khizar Rouf on 23 Jan 2020
Hi Sindar,
Thanks for providing the codes, but they are not working for my case. I may not have make clear what I am looking for. I am going to explain again. I hope it would be clear now.
I have three columns (not rows) as follows:
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]
I want to make a new array (n*2 (rows*column)) such that it has all elements of a3 in the first column. In the second column, it should have only corresponding values which will come from a2. If there is no value present, then a2 should remain blank for that particular value. For example, there will be a value for 0 but not for 1,2,3. Thanks

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!