How to rectify "arrays have incompatible sizes for this operation error" in this code: (Bioinformatics-related)
1 view (last 30 days)
Show older comments
ubq=getpdb('1UBQ')
for i=1:1000
if ubq.Model.Atom(i).AtomName == 'CA'
b=[ubq.Model.Atom(i).X,ubq.Model.Atom(i).Y,ubq.Model.Atom(i).Z]
end
end
0 Comments
Accepted Answer
Arthur Goldsipe
on 27 Jan 2023
Let me just start by sharing the fixed code. (I also fixed a bug in the first for loop.)
ubq=getpdb('1UBQ');
for i=1:numel(ubq.Model.Atom)
if ubq.Model.Atom(i).AtomName == "CA"
b=[ubq.Model.Atom(i).X,ubq.Model.Atom(i).Y,ubq.Model.Atom(i).Z];
end
end
b
Text in single quotes is a character vector. In this case, == will compare the two characters in CA one by one and error as you see if AtomName does not have exactly two characters. Also note that the result of this comparison will be a two-element logical vector with the result for each character. For example:
'Ca' == 'CA'
This behavior was introduced in the very first version of MATLAB. Character arrays are treated much like numeric arrays. And that was consistent with the focus of MATLAB on arrays in the early days. I should also mention another option here. You could instead compare two character vectors using the strcmp function:
strcmp('Ca','CA')
Now, this confused a lot of people. And wasn't very convenient for the kinds of text processing we do today. So a few years ago, MATLAB introduce a new way to store text: strings. That's what "CA" is. And strings behave more like what you would expect when processing text, including == meaning that you compare the entire contents of the string and return a single true or false indicating whether the text matches. You can find more information in MATLAB's documentation here.
Lastly, let me show you how I'd write this to avoid the for loop entirely and present all the results in a single matrix
isCA = ({ubq.Model.Atom.AtomName} == "CA");
caAtoms = ubq.Model.Atom(isCA);
coordinates = [caAtoms.X; caAtoms.Y; caAtoms.Z]'
More Answers (0)
See Also
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!