How do I return a matrix from a function?

조회 수: 2 (최근 30일)
Andrea Angella
Andrea Angella 2022년 3월 21일
답변: Image Analyst 2022년 3월 22일
Hello,
I am trying to write a very simple function that takes as an input an image in .tif format and returns a matrix of doubles where each value corresponds to the value of the pixel in that location of the image.
function A = readMyPicture (fileName)
arguments
fileName % This should be a string, the name of the image you want to read
end
A= double(imread(fileName)); % Converts image to matrix of doubles
end
This seems easy enough, however when I invoke the function (which is defined as a method of a handle class, but anyway I never had problems with other methods such as this one), it tells me the following error (the error appears in red in reality):
A = readMyPicture("example1.tif");
Check for missing argument or incorrect argument data type in call to function'readMyPicture'.
What am I doing wrong? I am very confused.
Thank you!
  댓글 수: 2
Michael Van de Graaff
Michael Van de Graaff 2022년 3월 22일
You code works for me just fine.
Dave B
Dave B 2022년 3월 22일
This code works, could it be that you have a previous version of readMyPicture on the path? Try calling:
which readMyPicture
to make sure you're pointing to the right one?
Or, just in case MATLAB is looking at an old cached copy of readMyPicture (shouldn't be the case, but worth a shot):
clear functions
(or just restart MATLAB)
Demo that what you have works (I cleaned up the spacing, but that was just me being obsessive, what you have is functional):
A = readMyPicture("peppers.png");
imshow(A./255)
function A = readMyPicture(fileName)
arguments
fileName % This should be a string, the name of the image you want to read
end
A = double(imread(fileName)); % Converts image to matrix of doubles
end

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

답변 (2개)

yanqi liu
yanqi liu 2022년 3월 22일
A = readMyPicture("cameraman.tif");
figure; imshow(A, []);
function A = readMyPicture (fileName)
A = [];
if nargin < 1
return
end
try
A= double(imread(fileName)); % Converts image to matrix of doubles
catch
end
end

Image Analyst
Image Analyst 2022년 3월 22일
Get rid of the "arguments" and "end" line. They are not needed. Or use @yanqi liu's solution for more robustness.

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by