why the real matrix becomes complex number when transfered to cell
Show older comments
why the real matrix becomes complex number when transfered to cell?
many thanks to all !
This is all of my code operations. FD is a matrix with all real number.
I actually want to get the result of fincost, but I found that the final output (fin_cost andTermfin_cost)contained complex numbers.
I use the code “isreal” to distinguish and finally find that FY contains complex numbers.
please help me see what the problem is.
Thanks to all !!
S=67
N=45% I'm sorry for a mistake that S and N are equal to 67 and 45 repectively.
FY=cell(S,S)
for i=1:1:S
for j=1:1:S
FY{i,j}=FD((i-1)*N+1:i*N,j)
end
end
containsComplex=~isreal(FY);
if containsComplex
disp('complex。');
else
disp('real。');
end
FY_shape=cell(S,S)
for i=1:1:S
for j=1:1:S
FY_shape{i,j}=FY{i,j}(1:44)
end
end
fin_cost=cell(S,1)
for i=1:1:S
fin_cost{i,1}=zeros(44,1)
for j=1:1:S
term3=FY_shape{i,i}.*FY_shape{j,j}
term4=FY_shape{i,j}.^2
term4(term4 == 0)=epsilon;
fin_cost{i,1}=fin_cost{i,1}+(term3./term4).^(1/14)
end
end
Termfin_cost= cell2mat(fin_cost)
3 Comments
Dyuman Joshi
on 29 Nov 2023
Edited: Dyuman Joshi
on 29 Nov 2023
Running the code on random data works properly, outputs real numbers as per the input.
Please attach the values for FD and N, so we can test your code, replicate the result you get and provide feedback accoringly.
S = 5;
FD = rand(S,S)
FY = cell(S,S);
N = 1;
for i=1:1:S
for j=1:1:S
FY{i,j}=FD((i-1)*N+1:i*N,j);
end
end
FY
Walter Roberson
on 29 Nov 2023
We recommend that you do not use i or j for loop control variables, as those are both also sqrt(-1)
There does not seem to be any complex number in the final output.
All values stored in the cell array are real, see below -
load('FD.mat');
%Check for values in FD
all(isreal(FD), 'all')
S=45;
N=6;
FY=cell(S,S);
for i=1:1:S
for j=1:1:S
FY{i,j}=FD((i-1)*N+1:i*N,j);
end
end
FY
%Check for values in FY
all(cellfun(@(x) all(isreal(x)), FY), 'all')
Answers (1)
You won't get complex output if FD is real. Check type of FD.
S=15; %smaller
N=6;
FD = rand(N*S, S);
FY=cell(S,S)
for i=1:1:S
for j=1:1:S
FY{i,j}=FD((i-1)*N+1:i*N,j);
end
end
FY
whos
Categories
Find more on Data Type Identification 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!