Matrix formation from column matrices using for loop
1 次查看(过去 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
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?
采纳的回答
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!