我有单元格数组:
im = {'A+','B-','B+','A+'; 'A-','B-', NaN, 'A+'};
我想循环遍历每一行以查看哪些具有' A&B;和' B'等于2.然后我将用NaN替换这些行。我有代码:
for ii = 1: size(im,1)
if (sum(strcmp('A+', im), 2) + sum(strcmp('A-', im), 2)) == 2 & (sum(strcmp('B+', im), 2) + sum(strcmp('B-', im), 2))== 2
im{ii, 1} = NaN;
im{ii, 2} = NaN;
im{ii, 3} = NaN;
im{ii, 4} = NaN;
end
end
当我从im
删除第二行时,我得到了ans:im = {NaN, NaN, NaN, NaN}
。但是,当我包含第二行时,im
仍然保持原样。请问,我的代码可能有什么问题?其次,是否有更好的方法来替换元素?
任何帮助或建议请???非常感谢。
答案 0 :(得分:0)
您的代码无法正常工作,因为在<?php
class Node{
public $left,$right;
public $data;
function __construct($data)
{
$this->left=$this->right=null;
$this->data = $data;
}
}
class Solution{
public function insert($root,$data){
if($root==null){
return new Node($data);
}
else{
if($data<=$root->data){
$cur=$this->insert($root->left,$data);
$root->left=$cur;
}
else{
$cur=$this->insert($root->right,$data);
$root->right=$cur;
}
return $root;
}
}
public function getHeight($root) {
$heightLeft = 0;
$heightRight = 0;
if ($root->left != null) {
$heightLeft = $this->getHeight($root->left) + 1;
}
if ($root->right != null) {
$heightRight = $this->getHeight($root->right) + 1;
}
echo "heightRigh is $heightRight\n";
echo "heightLeft is $heightLeft\n";
$ans = ($heightLeft > $heightRight ? $heightLeft : $heightRight);
return $ans;
}
}//End of Solution
$myTree=new Solution();
$root=null;
$T=intval(fgets(STDIN));
while($T-->0){
$data=intval(fgets(STDIN));
$root=$myTree->insert($root,$data);
}
$height=$myTree->getHeight($root);
echo $height;
?>
语句中,您正在检查整个单元格中的总和,而不仅仅是单行。你应该使用这样的东西:
if
另外,您可以更改下一行的四行,如下所示:
if (sum(strcmp('A+', im(ii,:)), 2) + sum(strcmp('A-', im(ii,:)), 2)) == 2 & (sum(strcmp('B+', im(ii,:)), 2) + sum(strcmp('B-', im(ii,:)), 2))== 2