How can I quickly compare sizes of two Matrices?
115 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Jakob Gillinger
il 23 Mag 2017
Risposto: Matthew Heberger
il 29 Dic 2022
I have two matrices of different sizes I'd like to compare before performing calculations with them - basically, I want to make sure their number of columns match. Now, as far as I can tell, I would have to use size() on both and compare their second value of the resulting vector, but since I can't index matrices that are temporary, I have to save the size vectors to a new variable, and then compare the indexed numbers. Is there a way to do it not only faster, but also without having to create a new variable?
0 Commenti
Risposta accettata
Più risposte (2)
Matthew Heberger
il 29 Dic 2022
Here is a good way to check that matrices A and B have the same size across all dimensions:
isequal(size(A), size(B))
This will return true if the matrices have the same size, and false if they have a different size. You can wrap it in an assert command if you want to raise an error and stop execution of the script when the two matrices are not the same size:
assert(isequal(size(A), size(B)))
Here is an example:
A = zeros(3, 1, 4);
B = zeros(3, 1, 4);
assert(isequal(size(A), size(B)))
% script will continue running after this...
This section will raise an error:
A = zeros(3, 1, 4);
B = zeros(3, 1);
assert(isequal(size(A), size(B)))
0 Commenti
Vedere anche
Categorie
Scopri di più su Matrix Indexing in Help Center e File Exchange
Prodotti
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!