type if x is a square matrix statement

Hi, How do I write the script for "If x is a square matrix funcz will be the 0"?
Thanks!

1 件のコメント

Jan
Jan 2017 年 10 月 27 日
A bullet-proof solution is not trivial. Therefore this question is more interesting than it looks like on first glance.

サインインしてコメントする。

回答 (3 件)

Stephen23
Stephen23 2017 年 10 月 26 日
編集済み: Stephen23 2017 年 10 月 26 日

1 投票

funcz = ~diff(size(x))

5 件のコメント

Jan
Jan 2017 年 10 月 26 日
This fails for a [2,2,2] array.
Stephen23
Stephen23 2017 年 10 月 26 日
編集済み: Stephen23 2017 年 10 月 26 日
@Jan Simon: not really, because Zhuoying Lin did not specify what should happen for ND arrays: it is pure speculation to say what funcz should be when x is an ND array.
Jan
Jan 2017 年 10 月 26 日
編集済み: Jan 2017 年 10 月 26 日
@Stephen: You are right. "0 if x is square matrix" might or might not imply that 1 is replied otherwise e.g. for nD arrays. Anyway, Lin will find enough details in this thread to solve the problem.
We need ~ismatrix(x), because 0 is wanted as output. But then ~diff(size(x)) replies a vector for nD arrays and the && is not applicable. What about:
~(ismatrix(x) && diff(size(x)))
Then the short-circuting should avoid the evaluation of the 2nd part, such that the "&& needs scalar input" problem does not occur.
Stephen23
Stephen23 2017 年 10 月 26 日
@Jan Simon: thank you, that is a tidy solution for ND arrays.
Zhuoying Lin
Zhuoying Lin 2017 年 10 月 26 日
Never thought about this question can be such complex. I just start learning Matlab and THANK YOU all for your answers!

サインインしてコメントする。

Jan
Jan 2017 年 10 月 26 日
編集済み: Jan 2017 年 10 月 26 日

1 投票

funcz = ~ismatrix(x) || (size(x, 1) ~= size(x, 2));
or with Matlab versions before R2010b:
funcz = (ndims(x) ~= 2) || (size(x, 1) ~= size(x, 2));
This rejects [0 x 1] matrices, but is is questionable, if an empty matrix can be non-square.
To reply funcz=0 for vectors:
funcz = (ndims(x) ~= 2) || all(size(x) ~= 1);
or with modern Matlab versions:
funcz = ~isvector(x)
michio
michio 2017 年 10 月 26 日

0 投票

[nRow,nCol] = size(x);
if nRow == nCol
funcz = 0;
end

3 件のコメント

Zhuoying Lin
Zhuoying Lin 2017 年 10 月 26 日
Thank you that helps a lot!
I have one more question:
What if now x is a vector how should I code it?
Jan
Jan 2017 年 10 月 26 日
編集済み: Jan 2017 年 10 月 26 日
This fails for a [4,2,2] array:
[nR, nC] = size(rand(4, 2, 2))
nR = 4, nC = 4
michio
michio 2017 年 10 月 27 日
Yes, it assumes that the array is 2D. Interesting thread :)

サインインしてコメントする。

カテゴリ

タグ

質問済み:

2017 年 10 月 26 日

コメント済み:

2017 年 10 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by