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

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)

% 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

if by "arrays", you mean rows:
a = [[0,4,5,6,7];[0.1,0.2,0.3,0.4,0.5]];
a1_new = [0:7];
[~,loc]=ismember(a(1,:),a1_new);
a_new = [a1_new;nan(size(a1_new))];
a_new(2,loc)=a(2,:);
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
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.

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

Asked:

on 22 Jan 2020

Commented:

on 23 Jan 2020

Community Treasure Hunt

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

Start Hunting!