2 differenct size arrays, I want to make the shorter array the same size as the longer by adding Zeros between the indices or the missing numbers and make them the same length

A=[1:10,1:10]'
B=[2 4 6 8 ; 3 3 3 3]'
The output I am trying to aim for is a matrix same size as A but column 2 has the values of B(:,2) see below
Output=[1:10 ; 0 3 0 3 0 3 0 3 0 0]'
I have tried various loops but I get indicies not same used vertcat to add to B the missing values this does not work either, tried all sorts for eg
for ii= 1:10
if ii~=B(ii,1)
B(ii,1)=vertcat(ii,B(:,1));
B(ii,2)=vertcat(0,B(:,2));
else
B(ii,1)=B(ii,1);
B(ii,2)=B(ii,2);
end
end

 Akzeptierte Antwort

dpb
dpb am 27 Aug. 2015
Bearbeitet: dpb am 29 Aug. 2015
No loops needed (or, in Matlab, wanted... :) )
>> O=[A(:,1) zeros(size(A,1),1)];
>> O(B(:,1),2)=B(:,2)
O =
1 0
2 3
3 0
4 3
5 0
6 3
7 0
8 3
9 0
10 0
>>
I'd note you're using the complex-conjugate transpose operator where you intend the simple array transpose which is given by the element-wise "dot operator" version, .' This makes no numerical difference with reals but is a bad habit to get into that can bite unexpectedly if/when one has complex numerical values. It's easier to develop the habit of using the right operator for the purpose from the git-go than have to break a bad habit later or debug a case that is wrong (or worse yet, not realize the answer gotten is wrong).

3 Kommentare

Many thanks this is much an easier way of doing it I thought you had to index each element and do a loop which would never work because the two matrices are different sizes. Great appreciate the help and quick response.
"...and do a loop which would never work"
Of course a loop can work, just that the power of Matlab is largely wasted if one uses them exclusively where vectorization is possible. But, to demonstrate, given the initialization step done above, then
for i=1:length(B)
O(B(i,1),2)=B(i,2);
end
You just have to recognize over what it is that you wish to/need to iterate.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Gefragt:

am 27 Aug. 2015

Bearbeitet:

dpb
am 29 Aug. 2015

Community Treasure Hunt

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

Start Hunting!

Translated by