MY function converte distance of km to miles or leagues. The things is that I dont sure if the IF ELSEIF AND END are in the correct positions, because it creates a error, but when I keep the first IF and the rest i put elseif elseif thats works, but I want to know how to put different ifs in the functions thanks.
function [Dout] = convertDistance(Din,uin,uout )
if strcmpi('mi',uin) && strcmpi('km',uout)
Dout= Din*(1/0.621);
elseif strcmpi('mi',uin) && strcmpi('li', uout)
Dout= Din*(3.45);
elseif strcmpi('mi', uin) && strcmpi('leagues', uout)
Dout= Din*(0.289)
if strcmpi('km', uin) && strcmpi('mi', uout)
Dout= Din*(0.621);
elseif strcmpi('km',uin) && strcmpi('li', uout)
Dout= Din*(2);
elseif strcmpi('km', uin) && strcmpi('leagues', uout)
Dout= Din*(0.18);
end
end
end

댓글 수: 1

Stephen23
Stephen23 2015년 9월 11일
@Rick Alarcon: today I formatted your code for you, but in the future you can do it yourself by selecting the code text and clicking the {} Code button that you will find above the textbox.
I also deleted your email address from the tags: this is a publicly accessible forum and it will only attract spam.

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

답변 (1개)

Stephen23
Stephen23 2015년 9월 11일
편집: Stephen23 2015년 9월 11일

0 개 추천

It helps everyone (especially yourself) when you write code using consistent indentation. Using consistent indentation makes code much more readable, and indicates the different parts of if statements and other operations. For the same reason do not use superfluous brackets. Place spaces on either side of '=' when you are allocating variables.
This is your code tidied up and with a few small changes:
function Dout = convertDistance(Din,uin,uout)
if strcmpi('mi',uin) && strcmpi('km',uout)
Dout = Din*(1/0.621);
elseif strcmpi('mi',uin) && strcmpi('li',uout)
Dout = Din*(3.45);
elseif strcmpi('mi',uin) && strcmpi('leagues',uout)
Dout = Din*(0.289);
elseif strcmpi('km',uin) && strcmpi('mi',uout)
Dout = Din*(0.621);
elseif strcmpi('km',uin) && strcmpi('li',uout)
Dout = Din*(2);
elseif strcmpi('km',uin) && strcmpi('leagues',uout)
Dout = Din*(0.18);
end
end
There are also much simpler, faster yet more versatile ways of achieving this functionality:
function Dout = convertDistance(Din,uin,uout)
X = {'km','mile','league','li'};%/km
Y = [ 1,0.6214, 0.18, 2];%/km
Dout = Y(strcmp(X,uout))*Din/Y(strcmp(X,uin));
end
This defines all of the numeric data in one vector, and calls strcmp only once for each of the input and output units. You can see that MATLAB is not like other low-level programming languages that rely on loops and if statements: making it work efficiently means learning how to take advantage of its features.

카테고리

도움말 센터File Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품

태그

아직 태그를 입력하지 않았습니다.

질문:

2015년 9월 11일

편집:

2015년 9월 11일

Community Treasure Hunt

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

Start Hunting!

Translated by