Matrix formation from column matrices using for loop

1 回表示 (過去 30 日間)
HEMRAJ PATEL
HEMRAJ PATEL 2021 年 11 月 13 日
コメント済み: HEMRAJ PATEL 2021 年 11 月 13 日
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 Center および File ExchangeMatrix Indexing についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by