How to insert an unknown number of coloumn in a Matrix?
15 views (last 30 days)
Show older comments
Hi everybody,
I'd like to add a number of coloumns specified in a variable to a matrix in certain positions.
The coloumns will be represented by arrays of just one value, the positions should divide equally (when possible) the matrix.
I'll make an exemple:
>> A=reshape(1:16,4,4)
A =
1 5 9 13
2 6 10 14
3 7 11 15
4 8 12 16
>> B(1,1:4)=-1;
>>B=B';
After modification I'll have:
For 3 coloumns to be inserted
NumCol=3;
A=
1 -1 5 -1 9 -1 13
2 -1 6 -1 10 -1 14
3 -1 7 -1 11 -1 15
4 -1 8 -1 12 -1 16
For just one
NumCol=1;
A=
1 5 -1 9 13
2 6 -1 10 14
3 7 -1 11 15
4 8 -1 12 16
I can find my self the way to understand where to insert coloumns. My problem is how??
Can somebody help me please?
0 Comments
Accepted Answer
madhan ravi
on 17 May 2019
Try this:
B=rand(3); % your initial matrix
[m,n]=size(B);
No_of_Columns=input('No of columns to be inserted')
disp('No of columns and NUMEL(where) should be equal')
where=input('inserting position_s')
Wanted=zeros(m,n+ncs)
A_constant=input('A scalar Value to be assigned')
Wanted(:,where)=A_constant
Wanted(:,setdiff(1:size(Wanted,2),where))=B
More Answers (1)
Guillaume
on 17 May 2019
It's hard to tell you a generic way without understanding how the insertion points are chosen.
In your first case, I would do:
newA = repmat(B, 1, size(A, 1) + NumCol); %fill with B
newA(:, 1:3:end) = A %copy A in odd columns
In your second case, I would do:
newA = [A(:, 1:2), B, A(:, 3:end)]
2 Comments
Guillaume
on 17 May 2019
This is how I'd do it then:
%A: a matrix of any size
%B: a column vector (or matrix) of the same height as A, to be inserted at regular interval in A
%NumCol: the number of times B must be inserted
splitdist = round(linspace(0, size(A, 2), NumCol + 2)); %find how to split A
newA = cell(1, 2*numel(splitdist) - 3);
newA(1:2:end) = mat2cell(A, size(A, 1), diff(splitdist)); %split and distribute A
newA(2:2:end) = {B}; %distribute B
newA = cell2mat(newA)
See Also
Categories
Find more on Matrix Indexing 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!