Matrix formation from column matrices using for loop

2 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2021-11-13
编辑:Stephen23 2021-11-13
"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 2021-11-13
It was generated through a image. I have got the solution of my querry. btw, thanks.

请先登录,再进行评论。

采纳的回答

Image Analyst
Image Analyst 2021-11-13
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by