Effacer les filtres
Effacer les filtres

Matrix formation from column matrices using for loop

2 vues (au cours des 30 derniers jours)
HEMRAJ PATEL
HEMRAJ PATEL le 13 Nov 2021
Commenté : HEMRAJ PATEL le 13 Nov 2021
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 commentaires
Stephen23
Stephen23 le 13 Nov 2021
Modifié(e) : Stephen23 le 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 le 13 Nov 2021
It was generated through a image. I have got the solution of my querry. btw, thanks.

Connectez-vous pour commenter.

Réponse acceptée

Image Analyst
Image Analyst le 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.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by