Function that returns 2 values

조회 수: 9 (최근 30일)
Spaceman
Spaceman 2024년 3월 19일
답변: Spaceman 2024년 3월 23일
Given : Your function header should look like the following:
function [Z,P]=myfun(A)
Find : Create a function myfun that accepts a matrix A as an input. The function should return 2 values...
  • Z - is the total number of elements in A that contain zeros
  • P - is the product of all values that are greater than 2
Issue: I created my function, and it makes sense to me, but I am still getting errors...
My Solution :
function [Z,P]=myfun(A)
Z=sum(A(A==0))
P=prod(A(A>2))
end
% Code used to call funtion:
% A=randi([-5 5],40);
% [Nzero,prod2]=myfun(A)
  댓글 수: 7
Steven Lord
Steven Lord 2024년 3월 21일
Recognizing what information a question is asking you is sometime difficult; schools often try to help students develop that skill via word problems starting at an early age, but it's not always easy.
Determining how to calculate that information can be just as tricky, though hopefully not as bad in MATLAB if you have access to the documentation. I tried searching for a phrase from your question in Help Center to see how helpful they'd be.
"number of elements" mostly found functions in the External Language Interfaces which would be good if you were writing code in a different language and calling it from MATLAB, but not quite what you're looking for.
Then I filtered the "number of elements" search to list just Functions (since I'm looking for a function to call to answer the question) and the first three hits look promising: numel, groupcounts, and nnz. numel and nnz are directly applicable to the question; groupcounts would require you to define "everything that's 0" as one group and "everything that's not 0" as another.
Spaceman
Spaceman 2024년 3월 23일
Genius. Thanks to ALL of your expert advice, I think I got it in the right direction.
function [Z,P]=myfun(A)
Z=length(A(A==0));
P=prod(A(A>2));
end
% Code used to call funtion:
A=randi([-5 5],40);
[Nzero,prod2]=myfun(A)

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

채택된 답변

Spaceman
Spaceman 2024년 3월 23일
function [Z,P]=myfun(A)
Z=length(A(A==0));
P=prod(A(A>2));
end
% Code used to call funtion:
A=randi([-5 5],40);
[Nzero,prod2]=myfun(A)

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

태그

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by