function - input and output matrix

I need to write a function that takes a matrix of any size, double all the elements that are positive and adds 10 to all the elements that are zero or negative. I can't use loops, only filters.
the input matrix is xin[n,m] sent by the script and the out variable is xout [n,m]
This is my code:
function xout = matrixfx(xin)
%matrixfx takes a matrix of any size, doubles all the elements that are positive and adds 10 to all
%the elements that are zero or negative.
[n,m] = size(xin);
xout = zeros(n,m);
mask = xin > 0;
xout(mask) = xin(mask) * 2;
xout(~mask) = xin(~mask) + 10;
end

댓글 수: 4

Steven Lord
Steven Lord 2021년 6월 21일
Okay, I can see one or two places where I might have suggestions on this code, but first what's your question about this code? What help are you looking for?
Mina
Mina 2021년 6월 21일
I need help to correct my mistakes.
I wrote a script to use the function and it is giving me this error "Operator '>' is not supported for operands of type 'struct'."
Steven Lord
Steven Lord 2021년 6월 21일
Okay, can you show us that script? I have a suspicion about what's causing the error but I'd need to see that script to confirm or refute that suspicion.
Mina
Mina 2021년 6월 21일
In the script, the function is used to manipulate the test data and then the elements of the matrix are added up.
x = load ('matrixA.mat');
y = matrixfx(x);
[rows,cols] = size(y);
total = 0;
for i = 1:rows
for j = 1:cols
total = total + y(i,j);
end
end

댓글을 달려면 로그인하십시오.

답변 (2개)

Steven Lord
Steven Lord 2021년 6월 22일

1 개 추천

My suspicion was correct. When you call load with an output argument, that output argument is a struct array with each variable in the MAT-file you load stored as a field of that struct. You just need to pull the data out of the struct.
mydata = load('census.mat')
mydata = struct with fields:
cdate: [21×1 double] pop: [21×1 double]
If I wanted to work with the date and population data from census.mat, I would need to use mydata.cdate and mydata.pop rather than mydata (the whole struct array), cdate (which doesn't exist; the data is in the field of mydata), or pop (which also doesn't exist.)
[p, s, mu] = polyfit(mydata.cdate, mydata.pop, 2); % Work with cdate and pop from census.mat
Jan
Jan 2021년 6월 21일
편집: Jan 2021년 6월 21일

0 개 추천

Your code is fine. The only problem is, that you call it with a struct. Unfortunately you show us the code, but not, how you cll it, but the error is there.
x = [-10, 0, 10; -0.1, -1, 0];
matrixfx(x) % Working!
ans = 2×3
0 10.0000 20.0000 9.9000 9.0000 10.0000
function xout = matrixfx(xin)
xout = zeros(size(xin));
mask = xin > 0;
xout(mask) = xin(mask) * 2;
xout(~mask) = xin(~mask) + 10;
end

카테고리

도움말 센터File Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

태그

질문:

2021년 6월 21일

답변:

2021년 6월 22일

Community Treasure Hunt

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

Start Hunting!

Translated by