Matrix formation from column matrices using for loop

1 view (last 30 days)
Suppose I have these four matrices
A=[2;3;7]; B=[2;3;8]; C=[1;3;7]; D=[2;56;7];
and i have to construct a matrix K= [2,2,1,2;3,3,3,56;7,8,7,7]
How will i do it using for loop. Because i have n no. of column arrays.
  2 Comments
Stephen23
Stephen23 on 13 Nov 2021
Edited: Stephen23 on 13 Nov 2021
"Because i have n no. of column arrays. "
Your task would be much simpler if your data was better designed, e.g. all column vectors were in one cell array.
Your current data design forces you into writing slow, inefficient, complex code (like Image Analyst shows below):
How did you get all of those separate variables into the MATLAB workspace? Did you write all of their names by hand?
HEMRAJ PATEL
HEMRAJ PATEL on 13 Nov 2021
It was generated through a image. I have got the solution of my querry. btw, thanks.

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 13 Nov 2021
Here's one way you can do it (as long as it's not your homework):
% Make up some random number of variables.
fontSize = 20;
markerSize = 40;
z = rand(3, 5)
A=[2;3;7]
B=[2;3;8]
C=[1;3;7]
D=[2;56;7]
% Get a list of those variables in memory.
s = whos
% Get the size of the first array, A. We need to know at least the name of the first variable.
[rows, columns] = size(A)
% See which other variables have the same size as A.
keepIt = false(1, length(s));
for k = 1 : length(s)
thiss = s(k)
if isequal(thiss.size, [rows, columns])
keepIt(k) = true;
end
end
% Extract only those variables that have the same size as A:
s = s(keepIt)
% "and i have to construct a matrix"
K = [2,2,1,2;3,3,3,56;7,8,7,7] % Desired output.
% Build up the desired output matrix using a for loop.
K = zeros(rows, length(s));
for col = 1 : length(s)
thiss = s(col);
K(:, col) = eval(thiss.name);
end
K % Display it in the command window.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!